Search code examples
angularsubject-observer

anugular 6 subscribe to subject from multiple component at a same time not working


I have two components(parent and child) and one service which are subscribed to a subject class at the same time. But when then subject class emit data using next method, only one component (child) is getting the data.

navbar.component.ts :(sender):

this.messageService.setClientUserAuth(this.respObject.details.actionDtls);

message.service.ts: (subscriber)

constructor(private route: Router, private _rest: RestApiService) {
  this.getClientUserAuth().subscribe(auth => {
    console.log('AUTH :' + JSON.stringify(auth));
  });
}
setClientUserAuth(id: any) {
   this.clientUserAuth.next(id);
}

getClientUserAuth(): Observable<any> {
   this.clientUserAuth = new Subject<any>();
   return this.clientUserAuth.asObservable();
}

base-template.component.ts : (Subscriber) (child )

ngOnInit() {

  this.messageService.getClientUserAuth().subscribe(auth => {
    console.log('------------>' + JSON.stringify(auth));
  });
}

action.component.ts (Subscriber)(Parent)

constructor(private _rest: RestApiService, private messageService: MessageService,
          private route: Router, private modalService: NgbModal, notifier: NotifierService) {
this.messageService.getClientUserAuth().subscribe(auth => {
  console.log('----::----->' + JSON.stringify(auth));
});
}

When the data comes from navbar component ,only base template subscription function got the data,But if I delete the subscription method from base template , then subscription method from action component get it. But I want the data inside all the components and services at a same time as they all are rendered at same time.How to achieve that.


Solution

  • Modify your service method, remove initialization of subject from the method "getClientUserAuth()", initialize your observable where you are defining it (also may be you want to make it private):

    private _clientUserAuth = new Subject<any>();
    getClientUserAuth(): Observable<any> {
       return this._clientUserAuth.asObservable();
    }
    
    setClientUserAuth(id: any) {
       this._clientUserAuth.next(id);
    }
    

    Every time any component, calls a subscribe over the return of getClientUserAuth(), you were ending up creating a new subject.