我希望一个组件调用一个调用http.post
的方法来设置一个行为主题,这样其他组件就可以访问这些数据了:
ngOnInit():void {
this.service.getAsync();
}
private _subject = new BehaviorSubject<any>([]);
subject$ = this._subject.asObservable();
getAsync() {
this.subject$ = this.http
.post(url, payload, options)
.map();
}
或者我应该做这样的事情:
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();
}
或类似的东西
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));
}
我不确定最有意义的是什么。给我1&amp; 3是最合乎逻辑的。但我看到其他人都使用了可观察模式的回归。然后当然有第四个选项,所有上述都是错误的。最好的方法是什么?
答案 0 :(得分:3)
我会这样做:
getAsync() {
this.http
.post(url, payload, options)
.map(t=>t.json())
.subscribe(t=> {
this._subject.next(t);
});
}