Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular subject subscription is not working

Tags:

angular

rxjs

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

like image 965
N1gthm4r3 Avatar asked Sep 20 '17 13:09

N1gthm4r3


2 Answers

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.

like image 143
bgraham Avatar answered Nov 09 '22 04:11

bgraham


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);
 }
like image 21
alexKhymenko Avatar answered Nov 09 '22 03:11

alexKhymenko