gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:41:07 24 4
gpt4 key购买 nike

我最近将我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com