sorry if this is trivial.
I'm new to Angular 4 and I'm struggling with a seemingly simple issue: having 2 or more components subscribe to an Observable
provided by a (login) Injectable
.
My goal is to have:
- A view invoke an event on
component1
component1
will invoke a method on alogin.service
login.service
will make a REST call- The response is "broadcast" using a
.next()
component1
andcomponent2
will react accordingly
This works perfectly when there is only 1 component but when I introduce another component that subscribe()
s to the Observable
, the 2nd component only gets notified at the very beginning (ie: it only receives one message) whereas component1
continues to work as expected and receives all messages.
I initially used Subject
and BehaviorSubject
with the asObservable()
method but then fell-back to plain Observable
with similar results.
Here is a snippet to help demonstrate:
login.service:
@Injectable()
export class LoginService {
private _loggedIn = new BehaviorSubject<booelan>(false);
public loggedIn$ = this._loggedIn.asObservable();
login() {
// call API service
this._loggedIn.next(true);
}
}
component1:
@Component({
selector: 'app-test1',
template: `<button (click)="login()"`,
providers: [ LoginService ]
})
export class AppTest1Component {
subscription: Subscription;
observer: Observer;
constructor(private loginService: LoginService) {}
ngOnInit() {
this.subscription = this.loginService.loggedIn$.subscribe(
state => { console.log('got event!', state); },
error => { console.log('Error:', error)},
() => { console.log('Complete'); }
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
component2:
@Component({
selector: 'app-test2',
template: `<button (click)="login()"`,
providers: [ LoginService ]
})
export class AppTest2Component {
subscription: Subscription;
observer: Observer;
constructor(private loginService: LoginService) {}
ngOnInit() {
this.subscription = this.loginService.loggedIn$.subscribe(
state => { console.log('got event!', state); },
error => { console.log('Error:', error)},
() => { console.log('Complete'); }
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
What is the simplest way to have several components subscribe to an Observable
that would presumably be provided by a service, and receive ALL messages?
The question posted here: Angular - shared service between components doesn't work does not related to Observables and Subscriptions.