Reputation: 7609
I am doing this in code in order to handle multiple views from multiple components
https://stackblitz.com/edit/angular-cy8jza (check the console for the error)
export class ViewGroup {
_onViewChanged: any;
OnViewChanged$ : Observable<any>;
_onViewAdded: any;
OnViewAdded$ : Observable<any>;
_onViewRemoved: any;
OnViewRemoved$ : Observable<any>;
viewsSet = new Set<string>();
currentView = "";
previousView = "";
constructor(){
this.OnViewChanged$ = Observable.create(obs => this._onViewChanged = obs);
this.OnViewAdded$ = Observable.create(obs => this._onViewAdded = obs);
this.OnViewRemoved$ = Observable.create(obs => this._onViewRemoved = obs);
}
}
somnwhere in the code I do
this._availableView.set(name, new ViewGroup());
and then call
this._availableView.get(group)._onViewAdded.next(view);
but I can't call the next on it, it s say undefined.
It's exactly the same procedure has
this.onGroupAdded$ = Observable.create(e => this._onGroupAdded = e)
but this one work in stackblitz.
EDIT : I found out that the method I pass inside the create is not called until I subscribe to it. I have to do this to make everything works :
this.OnViewChanged$ = Observable.create((obs) => {this._onViewAdded = obs});
this.OnViewAdded$ = Observable.create((obs) => {this._onViewAdded = obs});
this.OnViewRemoved$ = Observable.create((obs) => {this._onViewAdded = obs});
this.OnViewChanged$.subscribe();
this.OnViewAdded$.subscribe();
this.OnViewRemoved$.subscribe();
Is there any way to avoid it ?
Upvotes: 1
Views: 39
Reputation: 403
If I understand your case correctly, I think what you are looking for is a subject.
You are correct that observables don't run until they get subscribed to. You can find many references to that in all sorts of docs, for example: angular docs for observables.
So instead of creating the observables using the create method. Try declaring them as subjects. Check out how they are being used in angular docs here for more details: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service.
Upvotes: 2