I recently upgraded my Angular app from 4.3 to 5.0 and trying to play around some of the new features in it. One of them is removing dependancy from zone.js.
main.ts:
platformBrowserDynamic().bootstrapModule(AppModule, {
ngZone: 'noop',
});
component:
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();
}
}
In my component the ngOnDestroy() event is getting fired but ngOnInit() is not getting fired. And since ngOnInit() is not working, _onRouteChange never gets initialized and I get error on line this._onRouteChange.unsubscribe(); inside ngOnDestroy.
Error:
zone.js:690 Unhandled Promise rejection: Cannot read property 'unsubscribe' of undefined ; Zone: ; Task: Promise.then ; Value: TypeError: Cannot read property 'unsubscribe' of undefined