我在一个服务中有这个函数来从我的 API 获取数据
getProductById(id) {
return this.http.get<any>(piUrl + '/id', { params: id }).catch(this.errHandler);
}
我知道如何在我的组件中获取数据的唯一方法是像这样订阅。
this.myService.getProductById(id).subscribe(product => this.product = product);
但是一旦没有流,我只需要数据。我怎样才能得到一次数据?像这样。
this.myService.getProductById(id).once(product => this.product = product);
最佳答案
RXJS 5-6 方式将是
this.myService.getProductById(id).pipe(
first()
).subscribe(product => this.product = product);
或
this.myService.getProductById(id).pipe(
take(1)
).subscribe(product => this.product = product);
但是这个什么都不做也不需要因为HttpClient.get()
返回一个自完成的可观察对象,它发出一次并完成,订阅回调只会运行一次.所以这根本不会改变行为。
如果你愿意,你也可以
this.myService.getProductById(id).toPromise().then(product => this.product = product);
或
this.product = await this.myService.getProductById(id).toPromise();
关于Angular RXJS 无需订阅即可获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53638430/