gpt4 book ai didi

Angular observables - 如果没有订阅,我是否需要取消订阅?

转载 作者:行者123 更新时间:2023-12-01 23:16:00 25 4
gpt4 key购买 nike

我正在使用最新的 angular 8,并且对 observables 的概念很陌生。我的问题是,如果我直接调用一个 observable 而不是将其应用于订阅变量,我是否还需要取消订阅。以下是我想知道是否需要取消订阅的情况?
提前谢谢了

场景 1 - 从组件调用 httpService:

Service - httpService

getContactsHttp(){
let headers: any = new HttpHeaders(this.authService.getHeadersClient());
return this.httpClient.get('/contacts', {headers: headers})
.pipe(timeout(this.authService.getTimeoutLimit('normal')));
}

Component - Calling getContactsHttp and sorting response

getContacts() {
this.httpService.getContactsHttp().subscribe((data:any[])=>{
this.records = this.sortData(data)
})
}

场景 2 - 在组件中订阅的 observable
contacts$: new Subject<any[]>;

ngOnInit() {
this.getContacts();
this.contacts$.subscribe((data:any[])=>{
this.records = this.sortData(data);
})
}

getContacts() {
this.httpService.getContactsHttp().subscribe((data:ContactSearch[])=>{
this.contacts$.next(data);
})
}

服务 - httpService
     getContactsHttp(){
let headers: any = new HttpHeaders(this.authService.getHeadersClient());
return this.httpClient.get('/contacts', {headers: headers})
.pipe(timeout(this.authService.getTimeoutLimit('normal')));
}

最佳答案

简短的回答,是的,您仍然将组件中的 observable 取消订阅 avoid subscription leaks 。我的首选方法之一是使用 takeUntil() 运算符。

这就是您可以在组件中使用它的方式。

private unsubscribe: Subject<void> = new Subject();

ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}

getContacts() {
this.httpService.getContactsHttp()
.pipe(
takeUntil(this.unsubscribe),
).subscribe((data:ContactSearch[])=>{
this.contacts$.next(data);
});
}

正如 Brian Love 所解释的,

  • First, we import the takeUntil() operator as well as the Subject class.
  • Next, we define a private instance property named unsubscribe, which is a Subject.
  • We also create a new instance of Subject, defining the generic type as void. We use the takeUntil() operator in the pipe() method before invoking subscribe(), providing the unsubscribe observable.
  • In the ngOnDestroy() lifecycle method we emit a next() notification, and then complete() the unsubscribe observable. The subscription is now complete, and we have immediately unsubscribed when the ngOnDestroy() method is invoked during the lifecycle of our component.

关于Angular observables - 如果没有订阅,我是否需要取消订阅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460256/

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