0

I have a component which has two buttons.when i click on the first button as per the demo in the given plunker below it emits an event and my service function emits an async subject with some values...When i click on another button i am trying to call .next event again but it is throwing some error...I have made a pluker demo here http://plnkr.co/edit/wpyV7o9JErdQMzGFZ4wp?p=preview ...If i use subject it works fine but i dont want to use subject in this case...

export class ErrorService{
  latestError:AsyncSubject<string> = new AsyncSubject();

  Save() {
    this.latestError.next('form submitted');
    this.latestError.complete();
  }

  Update(){
    this.latestError.next('form updated');
    this.latestError.complete();
  }
}

This is my service class and this is how i am calling .next event for async subject.

  this.service.latestError.subscribe(
err=> {
  console.log('result = '+err);
  this.result=err;
},
err => {
  console.log('err');
},
() => {
  console.log('complete');
});

And this is how i have subscribed the async subject...The click event works fine for the first time but when i click the another button it throws error.Somebody please help me to solve this error...How can i call .next() for second time using my async subject...Thanks in advance

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
Raja Reddy
  • 417
  • 2
  • 5
  • 11

2 Answers2

2

Try this

this.service.latestError.subscribe(
err=> {
  this.service.latestError = new AsyncSubject(); // this set isStopped property to false again
  console.log('result = '+err);
  this.result=err;
},
err => {
  console.log('err');
},
() => {
  console.log('complete');
});
bpena
  • 21
  • 3
1

It's because you call the complete method on the subject. It ends the data flow chain and you can't receive events anymore.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • If i dont call the complete method it is not emitting any values even if i click button for first time...Is there any other alternative to emit data everytime .next() is called using async subject? – Raja Reddy Apr 04 '16 at 14:21
  • What is your use case? Is using the AsyncSubject class necessary? – Thierry Templier Apr 04 '16 at 14:23
  • Yea because i am loading a component dynamically using DCL and making a service call using the same button click event. if i use subject,by the time component is loaded the .next() statement is executed so it is compulsary for me to use async in my case – Raja Reddy Apr 04 '16 at 14:27