假设我在提供程序中有一个这样的函数:
getAll(): Observable<CarModel[]> {
return this.http.get<CarModel[]>(this.carUrl);
}
在一个组件中,我有一个使用提供程序的这个函数的函数:
getCars() {
const that = this;
this.carService.getAll().subscribe(function(cars) {
that.factoryService.setCars(cars);
this.unsubscribe();
});
}
是否可以将其替换为使用 take
运算符以避免调用unsubscribe()
的函数?
getCars() {
const that = this;
this.carService.getAll().take(1).subscribe(function(cars) {
that.factoryService.setCars(cars);
});
}
我想知道当与Angular的Httpclient的方法一起使用时,这是否会有任何意外或不需要的行为?我从未见过Angular的Httpclient像这样使用-这就是我问的原因。
请求完成后,HttpClient 在流上调用complete
。调用完整信号的 Observable,表示不会发出更多值,因此任何订阅者都不会收到更多值。这意味着没有理由取消订阅或将take
与 http 请求一起使用。
getAll(): Observable<CarModel[]> {
return this.http.get<CarModel[]>(this.carUrl); // <- Emits once and completes
}
从文档中查看此部分。注意:
来自 HttpClient 的可观察量始终发出单个值,然后完成,不再发出。
作为你,我以前从未见过这样。
我曾经将所有 http 请求可观察量转换为承诺:
在 MDN 站点中,您可以找到以下内容: The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
this.carService.getAll()
.toPromise()
.then((cars) => {
that.factoryService.setCars(cars);
}).catch((error) => {
console.error(error);
});