N1gthm4r3
N1gthm4r3

Reputation: 785

Angular subject subscription is not working

I have a service ->

subject = new Subject<any>();

  constructor (){
    this.subject.next('hello');
  }

  getsubject():Observable<any>{
    return this.subject.asObservable();
  }

and component ->

name:string;
  subscription : Subscription;
  constructor(private serv:SService) {
    this.subscription=this.serv.getsubject().subscribe(message=>{console.log('hello');});
  }

as you can see, i'm passing hello message from service to subscribers, but in component subscriber is not getting that value, even it's not logging any word.

plunker example

Upvotes: 14

Views: 28234

Answers (4)

Code Spy
Code Spy

Reputation: 9964

In my case the issue was this:

let mySubject = new Subject<number>();
mySubject.next(1);
mySubject.subscribe(x => console.log("First Subscription : " + x));

which is wrong, as Subject does not keep history of values, the 1 value was getting lost as I was subscribing at last.

So I changed it to this to make it work.

let mySubject = new Subject<number>();
mySubject.subscribe(x => console.log("First Subscription : " + x));
mySubject.next(1);

Debug tip, add break points on next and subscribe and make sure the subscribe breaks at the last.

If this is not possible, just replace Subject with BehaviourSubject which can help to emit value at point you subscribe to it

Upvotes: 3

enyoucky
enyoucky

Reputation: 123

If your subscriber is component file, one of the reason can be disremembering of adding selector of your component somewhere in your application. You must register component for example in app.component.html.

Upvotes: 1

bgraham
bgraham

Reputation: 1997

The observable probably fires from the constructor before the component subscribes to it. So the component misses the message.

Instead of putting this.subject.next('hello') in the constructor, make a method.

  sendMessage (){
    this.subject.next('hello');
  }

You can then call the this.serv.sendMessage() from the component, and it will already be subscribed.

Alternatively you can look into BehaviorSubject which will hold onto the most recent value, and give it right away when something subscribes to it.

Upvotes: 15

alexKhymenko
alexKhymenko

Reputation: 5598

Its working. plunker you need to add this code. So subject will emit value if nobody subscribed to it at that time nobody will know that it emitted value. and when somebody subscribe it will not emit last value(BehaviorSubject will) .

 passToServ() {
   this.subject.next(2);
 }

Upvotes: 3

Related Questions