【发布时间】:2019-11-08 21:18:55
【问题描述】:
我正在使用最新的 Angular 8,并且对 observables 的概念很陌生。我有一个问题,如果我直接调用一个可观察对象而不将其应用于订阅变量,我还需要取消订阅吗?以下是我想知道是否需要退订的场景? 非常感谢提前
场景 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')));
}
【问题讨论】:
-
回答下面的评论,不退订是内存泄漏。
标签: angular rxjs observable