在Angular 5中禁用zone.js后ngOnInit不会触发

Sau*_*kar 5 javascript angular2-changedetection zone.js angular angular5

我最近将Angular应用程序从4.3升级到5.0,并尝试使用其中的一些新功能。其中之一是从zone.js中删除依赖项。

main.ts:

platformBrowserDynamic().bootstrapModule(AppModule, {
  ngZone: 'noop',
});
Run Code Online (Sandbox Code Playgroud)

零件:

import { ApplicationRef, Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Subscription } from 'rxjs/Rx';

import { MenuService } from '../../services/menu.service';

@Component({
  selector: 'ba-menu',
  templateUrl: './baMenu.html',
  styleUrls: ['./baMenu.scss'],
})
export class BaMenu {
  menuItems: any[];
  protected _menuItemsSub: Subscription;
  protected _onRouteChange: Subscription;

  constructor(public _router: Router, public _service: MenuService, public app: ApplicationRef) {
    console.log('constructor triggered'); //This worked
    this.app.tick();
  }


  ngOnInit(): void {
    console.log('ngOnInit() triggered'); //This doesn't worked
    this._onRouteChange = this._router.events.subscribe((event) => {

      if (event instanceof NavigationEnd) {
        if (this.menuItems) {
          this.selectMenuAndNotify();
        } else {
          // on page load we have to wait as event is fired before menu elements are prepared
          setTimeout(() => this.selectMenuAndNotify());
        }
      }
    });

    this._menuItemsSub = this._service.menuItems.subscribe(this.updateMenu.bind(this));
  }

  public ngOnDestroy(): void {
    console.log('ngOnDestroy() triggered'); //This worked
    this._onRouteChange.unsubscribe();
    this._menuItemsSub.unsubscribe();
  }

}
Run Code Online (Sandbox Code Playgroud)

在我的组件中,会触发ngOnDestroy()事件,但不会触发ngOnInit()。并且由于ngOnInit()无法正常工作,因此_onRouteChange从未初始化,并且在此行上出现错误。_onRouteChange.unsubscribe(); 在ngOnDestroy中。

错误:

zone.js:690未处理的承诺拒绝:无法读取undefined的属性“ unsubscribe”;区域:任务:Promise.then; 值:TypeError:无法读取未定义的属性“取消订阅”

sta*_*ght -2

您还没有OnInit在组件代码中实现。

//Change here
export class BaMenu implements OnInit {
  menuItems: any[];
  protected _menuItemsSub: Subscription;
  protected _onRouteChange: Subscription;

  ngOnInit() {
     //Some code
  }
  //Some code

}
Run Code Online (Sandbox Code Playgroud)