gpt4 book ai didi

Angular:每次需要更新时我都应该订阅()到http.get()吗?

转载 作者:行者123 更新时间:2023-12-05 06:30:35 27 4
gpt4 key购买 nike

我想知道我是否使用 Observable.subscribe() 的次数太多了。

在我的组件类中,我有一个函数 loadData()。它调用另一个函数 this.service.getData(),该函数使用 HttpClient.get() 向服务器执行 HTTP 请求。

目前在我的函数 loadData() 中,我订阅了 this.service.getData() 的结果。

每次用户点击“更新”按钮时,我都想调用我的函数 loadData()。

问题

  • 如果我每次需要执行 HTTP 请求时都调用我的函数 loadData(),我会创建同样多的订阅者吗?
  • 是否存在内存泄漏的风险?
  • 如果是这样,您知道我应该如何重构我的代码吗?

答案

代码示例

private loadData() {
this.loading = true;
const subscription = this.service.getData()
.pipe(
// console.log() with a delay added for test - START
map(val => {
window.setTimeout(() => {
// This will print true.
console.log('After delay: Is Subscriber closed?', subscription.closed);
}, 10);
return val;
}),
// console.log() with a delay added for test - END
takeUntil(this.ngUnsubscribe))
.subscribe(data => {
this.data = data;
// This will print false.
console.log('Is Subscriber closed?', subscription.closed);
},
error => {
console.error(error);
throw error;
},
() => {
this.loading = false;
});
}
getData(): Observable<DataObject> {
const uri = encodeURI(this.configService.getUri());
const headers = new HttpHeaders();
if (this.pipelineEtag) {
headers.set('If-None-Match', this.pipelineEtag);
}
return this.http.get(uri, {
headers: headers,
observe: 'response'
}).pipe(
map(resp => this.processResponse(resp)),
catchError(error => this.handleError(error, this.envProduction))
);
}

最佳答案

每次 HTTP 调用返回一个值时,Observable 就完成了。所以在服务中做这样的事情是安全的

loadData() { 

return this.http.get<Data>(dataUrl).pipe(
// tap(data => console.log(data)), // eyeball results in the console
catchError(err => this.handleError(err))
);

}

然后调用

this.service.loadData().subscribe((data:Data) => do somthing)

您甚至可以调用 exhaustMap 或 switchMap 来控制 Observable 流程,以免“提示”服务器太多时间

关于Angular:每次需要更新时我都应该订阅()到http.get()吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52223727/

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