我最近将我的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永远不会被初始化,并且我在ngOnDestroy中的 this._onRouteChange.unsubscribe(); 上得到错误。
错误:
zone.js:690未处理承诺拒绝:无法读取属性 '取消订阅'未定义的;区域:;任务:Promise.then; 值:TypeError:无法读取属性'取消订阅'未定义的
答案 0 :(得分:-1)
您尚未在组件代码中实施OnInit
。
//Change here
export class BaMenu implements OnInit {
menuItems: any[];
protected _menuItemsSub: Subscription;
protected _onRouteChange: Subscription;
ngOnInit() {
//Some code
}
//Some code
}