当在组件中有异步相关操作的时候,组件销毁时。该异步操作依然会在执行
- 组件被销毁,但是还有相关异步在操作组件中视图(组件模板、指令相关操作)。导致报错:
Uncaught (in promise): Error: NG0911: View has already been destroyed.
- 那时候就需要在组件销毁的时候清除异步操作(不限制于http请求,setTimeout等异步操作)
- 由于HttpClient基于rxjs封装的,所以在组件的destroy钩子中使用rxjs清除对应的请求
import { ElementRef, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@ViewChild('tagInput', { static: true }) tagInput!: ElementRef<HTMLInputElement>;
export class ProAccountCenterComponent implements OnInit, OnDestroy {
private httpSubscription: Subscription = new Subscription();
private ngUnsubscribe: Subject<void> = new Subject<void>();
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.httpSubscription = this.http.get('https://api.example.com/list')
.subscribe(res => {
this.tagInput.value = res
});
this.loadViewByData()
}
ngOnDestroy(){
this.ngUnsubscribe.next()
this.ngUnsubscribe.complete()
this.httpSubscription.unsubscribe()
}
async loadViewByData(){
const res = await firstValueForm(
this.http.get('https://api.example.com/data')
.pipe(takeUntil(this.ngUnsubscribe))
)
this.tagInput.value = res
}
}