Error: ViewDestroyedError: Attempt to use a destroyed view: detectChanges at viewDestroyedError
I get this error when going to another page while trying to trigger change detection by using detectChanges
method in a component. I discovered that I don't get the error if I used markForCheck
method. I'm aware of the difference from the two methods but I just don't get why detectChanges
would cause this error during the destroy process. Any ideas?
import { Component, ChangeDetectorRef, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class ChildComponent implements OnInit {
data: any;
constructor(
private changeDetector: ChangeDetectorRef,
private somethingService: SomethingService
) {
}
ngOnInit() {
this.somethingService.getData().subscribe(data => {
this.data = data;
this.changeDetector.detectChanges();
});
}
}
There is no need to call detectChanges
If you still want to use it you can also just ensure the observable is unsubscribed on destroy.
serviceSubscription:any
ngOnInit() {
this.serviceSubscription = this.somethingService.getData().subscribe(data => {
this.data = data;
this.changeDetector.detectChanges();
});
}
ngOnDestroy() {
this.serviceSubscription.unsubscribe();
}
Another way is to use the async pipe
ngOnInit() {
this.data$ = this.somethingService.getData();
}
with
<div *ngFor="let item of data$ | async">
(or similar)
The async
pipe will subscribe/unsubscribe automatically
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With