Learning observable and Angular2. I want to find out the BEST practices of sharing an observable between multiple Angular2 components. As observable default is NOT multicast. So each subscription in different part of my app will open an new stream (call my API server again!). Also, I need to share the value and get the latest value of that observable. I hear people using behavior subject. But that is really confusing and I can not find a good example for that. Here is how I approach this in my authService:
userInfo$: Observable<User>;
this.userInfo$ = this.authInfo$
.switchMap(authInfo => this.findUserByuid(authInfo.$uid)) // finding user info base on authInfo turn or not.
.publishReplay(1).refCount();
And in my Angular2 component, I do this:
this.authService.userInfo$.subscribe(user => {
console.log (user);
this.user = user;
})
Everything works. But I wonder could I use behavior subject in this case? Am I doing everything right by sharing the userInfo$ among ALL my components (all my components which need userinfo$ will do the above code to subscribe to it)?