Angular2 ViewDestroyedError:尝试使用已销毁的视图

时间:2017-07-10 08:30:47

标签: angular typescript

我的angular2出现了一个小错误。我在这个论坛和其他网站上查找了一些信息,但不幸的是没有成功。也许有人帮我解决这个错误。这是完整的错误消息:

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>]

我的组件:

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; 
    }
  }
}

用户注销时会出现错误,并且运行logOutClick函数。并且同时函数checkIfClient的结果发生了变化。我试图通过使用ChangeDetectionStrategy解决这个问题,但没有成功。 如果有人知道如何解决,请帮帮我:)谢谢。

0 个答案:

没有答案