【发布时间】:2020-02-04 14:40:08
【问题描述】:
我想了解为什么在下面给出的代码中使用take 运算符。
private _places = new BehaviorSubject<Place[]>(
// places for initialization
);
get places() {
return this._places.asObservable();
}
addPlace(title: string, description: string, price: number)
{
generatedId: string;
newPlace: Place;
// code to initialize newPlace
return this.http.post<{name: string}>(
'https://ionic-angular-ef2f8.firebaseio.com/offered-places.json',
{...newPlace, id: null})
.pipe(
switchMap(response => {
generatedId = response.name;
return this.places;
}),
take(1),
tap(places => {
newPlace.id = generatedId;
this._places.next(places.concat(newPlace));
})
);
}
post 请求返回一个Observable,我们在switchMap 运算符中从中获取一个值(注意,在调用switchMap 之前我们没有take 一个值)。在switchMap 中,我们将可观察对象替换为从_places 获得的新可观察对象,即BehaviourSubject 对象。在switchMap 之后,我们使用take 运算符。
为什么我们不跳过take 运算符,直接使用tap?我们是否take 来自可观察对象的值,因为可观察对象是从主题生成的?谁能详细解释take操作符的用例?
更新
我怀疑我应该在switchMap 之后使用take 运算符的原因是switchMap 返回一个从BehaviorSubject 类型的对象接收到的可观察对象,该对象包含发出的值。可以订阅这样的 BehaviorSubject 对象和 take 最新发出的值 - 这正是我所做的。
【问题讨论】:
标签: rxjs