Reputation: 671
I want a component to call a method which calls a http.post
which sets a behavior subject so then other components have access to the data some thing like this:
ngOnInit():void {
this.service.getAsync();
}
private _subject = new BehaviorSubject<any>([]);
subject$ = this._subject.asObservable();
getAsync() {
this.subject$ = this.http
.post(url, payload, options)
.map();
}
Or should I be looking to do something like this:
ngOnInit():void {
this.service.setAsync();
}
private _subject = new BehaviorSubject<any>([]);
subject$ = this._subject.asObservable();
setAsync(){
this.subject$ = this.getAsync();
}
getAsync(): Observable<any[]> {
return this.http
.post(url, payload, options)
.map();
}
Or something like this
ngOnInit():void {
this.service.getAsync();
}
private _subject = new BehaviorSubject<any>([]);
subject$ = this._subject.asObservable();
getAsync() {
this.http
.post(url, payload, options)
.map(data => this._subject.next(data));
}
I'm not sure of what makes the most sense. To me 1 & 3 are the most logical. But I see everyone else using the return of an observable pattern. Then of course there is the 4th option that all of the above are wrong. What's the best way to do this?
Upvotes: 1
Views: 736
Reputation: 52837
I would do this:
getAsync() {
this.http
.post(url, payload, options)
.map(t=>t.json())
.subscribe(t=> {
this._subject.next(t);
});
}
Upvotes: 3