我最近将我的 Angular 应用程序从 4.3 升级到了 5.0,并尝试使用其中的一些新功能。其中之一是从 zone.js 中删除依赖关系。
main.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 永远不会被初始化,我在this._onRouteChange.unsubscribe(); 在 ngOnDestroy 内部。
错误:
zone.js:690 未处理的承诺拒绝:无法读取未定义的属性“取消订阅”;区域:; 任务:Promise.then;值:TypeError:无法读取未定义的属性“取消订阅”