Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does detectChanges method cause "Attempt to use a destroyed view" Error?

Tags:

angular

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();
        });
    }
}
like image 733
DongBin Kim Avatar asked Jan 29 '23 01:01

DongBin Kim


1 Answers

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

like image 96
Günter Zöchbauer Avatar answered Feb 05 '23 17:02

Günter Zöchbauer