2

I got a minor error with my angular2. I looked for an information in this forum and other web sites but unfortinaly without success. Maybe somebody help me to resolve this error. This the full error message:

NavbarComponent.html:46 ERROR Error: ViewDestroyedError: Attempt to use a destroyed view: detectChanges
at viewDestroyedError (core.es5.js:8636) [angular]
at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12610) [angular]
at checkAndUpdateView (core.es5.js:12025) [angular]
at callWithDebugContext (core.es5.js:13013) [angular]
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.es5.js:12553) [angular]
at ViewRef_.detectChanges (core.es5.js:10122) [angular]
at vendor.bundle.js:71694:26 [angular]
at Object.onInvokeTask (core.es5.js:4116) [angular]
at ZoneDelegate.invokeTask (zone.js:397) [angular]
at Zone.runTask (zone.js:165) [<root> => angular]
at ZoneTask.invoke (zone.js:460) [<root>]
at timer (zone.js:1540) [<root>]

And my Component:

import {
  Component,
  OnInit,
  OnDestroy,
  ChangeDetectionStrategy,
  ChangeDetectorRef
} from '@angular/core';

@Component({
  selector: 'app-navbar',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit, OnDestroy {
  constructor(
    private home:HomeService,
    private userServ: UserService,
    private flashMess: FlashMessagesService,
    private router: Router,
    private ref: ChangeDetectorRef
  ) {
    setInterval(() => {
      this.ref.markForCheck();
    }, 1000);
  }

  ngOnInit() {   
    this.homeObserv =  this.home.getHome().subscribe(data => {
      if(data) {
        this.homeData = data;
        this.companyPhones = this.homeData[0].phones; 
        this.companyAddress = this.homeData[0].companyAddress; 
      }
    });
  }

  ngOnDestroy() {
    this.ref.detach(); 
    this.homeObserv.unsubscribe();
  }


  logOutClick() {
    this.flashMess.show('You are now logged out', {
      cssClass: 'alert-success',
      timeOut: 5000
    });
    this.router.navigate(['/']);
    this.userServ.logout();
  }

  checkIfClient() {
    if(this.userServ.loggedIn()) {
      return true; 
    } else {
      return false; 
    }
  }
}

Error is appear when the user logout, and the logOutClick function is run. And in the same time the result of function checkIfClient is change. I tried to fix this by using ChangeDetectionStrategy, but with no success. If someone have an idea how to fix, please help me:) Thank's.

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Andrew Olinevich
  • 61
  • 1
  • 1
  • 8

0 Answers0