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

标签 javascript angular angular2-changedetection angular5 zone.js

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

ma​​in.ts:

platformBrowserDynamic().bootstrapModule(AppModule, {
  ngZone: 'noop',
});

组件:

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

}

在我的组件中,ngOnDestroy() 事件被触发但 ngOnInit() 没有被触发。由于 ngOnInit() 不工作,_onRouteChange 永远不会被初始化,我在 ngOnDestroy 内的行 this._onRouteChange.unsubscribe(); 上收到错误。

错误:

zone.js:690 Unhandled Promise rejection: Cannot read property 'unsubscribe' of undefined ; Zone: ; Task: Promise.then ; Value: TypeError: Cannot read property 'unsubscribe' of undefined

最佳答案

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

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

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

}

关于javascript - 在 Angular 5 中禁用 zone.js 后不会触发 ngOnInit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47256527/

相关文章:

javascript - jquery(或纯 js)将更改事件绑定(bind)到数组中对象的属性

javascript - 自定义鼠标光标 + IN word

resize - 如何对 div 调整大小执行变化检测

javascript - 在模板中使用 Angular Reactive Forms .get() 方法会导致不必要的方法调用,如组件方法吗?

javascript - Angular2 从应用程序外部调用公开方法并丢失更改绑定(bind)

Javascript从字符串中获取顶级域名

javascript - 为什么 Javascript 在 Google 的新样式 Chrome 扩展选项页面示例代码中不起作用?

angular - 如何在 Angular 中使用 *ngFor 设置 formControlNames?

javascript - 缩放和平移后fabricJS中的对象对齐

angular - 应用程序 Angular2 之外的路由