问题描述: 在使用Angular进行路由导航时,可能会遇到以下错误信息: ViewDestroyedError: 尝试使用已销毁的视图: detectChanges
解决方法: 出现此错误的原因是尝试在已销毁的视图上调用detectChanges方法。解决方法如下:
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnDestroy {
private subscription: Subscription;
constructor(private myService: MyService) { }
ngOnInit() {
this.subscription = this.myService.someObservable.subscribe(() => {
// Do something
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
import { Component, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnDestroy {
private unsubscribe$ = new Subject();
constructor(private myService: MyService) { }
ngOnInit() {
this.myService.someObservable
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => {
// Do something
});
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
通过以上解决方法,可以避免在Angular路由导航中出现ViewDestroyedError错误。