最近、Angular アプリを 4.3 から 5.0 にアップグレードし、その新機能のいくつかを試してみました。それらの 1 つは、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 拒否: undefined のプロパティ 'unsubscribe' を読み取ることができません。ゾーン: ; タスク: Promise.then ; 値: TypeError: 未定義のプロパティ 'unsubscribe' を読み取ることができません