gpt4 book ai didi

Angular RXJS 无需订阅即可获取数据

转载 作者:行者123 更新时间:2023-12-02 20:10:55 24 4
gpt4 key购买 nike

我在一个服务中有这个函数来从我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com