0

I am trying to use the "Subject" class in angular2 to broadcast an event as an observable, from a service to all the components that have the instance of that service in them.

in my service, I have the following:

private loggedIn = new Subject<boolean>();

isUserLoggedIn(): Observable<boolean> 
{
    return this.loggedIn.asObservable();
}

test() 
{
  this.loggedIn.next(true);
}

And then in the component that uses this service, I have (_auth is the same service defined above):

ngOnInit()
    {
        console.log("yay!");
        this._auth.isUserLoggedIn()
            .subscribe(
                d => {
                    console.log(d);
                },
                d => {
                    console.log(d);
                },
                () => {
                    console.log("Done!");
                }
            );
    }

Now the issue is if I call the service's method this._auth.test(); from within this same component, everything works fine and the console.log lines get executed in this component. But if the service's method is called from another component, this component does not get triggered to run the console.log lines.

How can I make sure that the code in this component runs even if the service's method is triggered by another component? (Assume both components are rendered at the same time).

Thanks!

Behrooz
  • 1,895
  • 4
  • 31
  • 47

1 Answers1

2

Don't provide the service on each component, only provide it in

@NgModule({ 
  providers: MySharedService, 
  ...
})
export class AppModule {}

otherwise a new service instance is created for each component (for each provider)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I have already done that. The shared service is only provided in the AppModule and nowhere else. – Behrooz Jul 18 '17 at 17:45
  • 1
    Then the only thing I can imagine is, that the components subscribe only **after** the event was sent. You can try to verify by using a `BehaviorSubject` instead of `Subject`. – Günter Zöchbauer Jul 18 '17 at 17:48
  • Can you elaborate on the BehaviourSubject? – Behrooz Jul 18 '17 at 17:52
  • 1
    `BehaviorSubject` remembers the last emitted event and immediately emits this value to new subscribers. This way subscribers subscribing after the event was emitted also get the event. – Günter Zöchbauer Jul 18 '17 at 17:54
  • And all I have to do is replace it with Subject? What package is it in if I want to import it? – Behrooz Jul 18 '17 at 17:56
  • 1
    https://stackoverflow.com/questions/36701041/cannot-find-module-rxjs-subject-behaviorsubject. Yes, just replace `Subject` – Günter Zöchbauer Jul 18 '17 at 17:57