MrRobot
MrRobot

Reputation: 1167

Subject not returning anything

I'm having trouble with Subject on Angular.

On my service I have formSendStatus = new Subject<boolean>();

I have a form.component that will set the next value for that subject like this: myservice.formSendStatus.next(true);

Then, I have another component that subscribes to it:

ngOnInit() {
   myservice.formSendStatus.subscribe(
      data => console.log(data)
   );
}

I get nothing on the console. Am I doing something wrong?

Upvotes: 0

Views: 501

Answers (2)

bryan60
bryan60

Reputation: 29315

When using a subject, you have to call next() on it for it to emit a value. In the case of a plain subject (which you’re using here), you need to make sure you’re already subscribed when next is called. If thats not possible, you may use a BehaviorSubject or a ReplaySubject since they will cache values and emit them to new subscribers.

formSendStatus = new ReplaySubject<boolean>(1) // the number is the number of values to cache, 1 means only store and emit the last value, no number means store and cache all values

formSendStatus = new BehaviorSubject<boolean>(false); // behavior subjects require a default value, in this case false is the default value

Upvotes: 1

German Quinteros
German Quinteros

Reputation: 1930

Your problem is that you shouldn't subscribe to formSendStatus instead of that you should to subscribe to a property that is observable of formSendStatus like this:

export class MyService {
   formSendStatus: Subject<boolean>;
   formSend$: Observable<boolean>;
   constructor() {
     this.formSendStatus = new Subject<boolean>();
     this.formSend$ = this.formSendStatus.asObservable();
   }
}

Then in your component you should do this:

ngOnInit() {
   myservice.formSend$.subscribe(
      data => console.log(data)
   );
}

Now every time that you emit a value with next() in formSendStatus the component will know by the observable formSend$

Upvotes: 1

Related Questions