ngOnDestroy is called when loading the page for the first time

时间:2019-04-08 13:58:38

标签: angular lifecycle

When I load the page first time, on some pages it shows unsubscribe error in ngOnDestroy as I am unsubscribing subscribes in it.

I am not sure why ngOnDestroy is called at the init of the component.

enter image description here

enter image description here

This is the error what I see when the page is first loaded.

I thought this was some issue from angular2-multiselect-dropdown but in some other component, its own ngOnDestory is called as well and says subscription to unsubscribe is not defined.

So I added if condition to remove the error message. enter image description here

This is the creation of the subscription.

enter image description here enter image description here

Actually I don't think it has any other problem in defining the observable.

So is this a problem with angular component lifecycle or possibly an issue from angular2-multiselect-dropdown?

I didn't see this error before and not sure what I did wrong. Can anyone had similar issue or help me on this? Thanks in advance.

3 个答案:

答案 0 :(得分:0)

您的rxjs版本是什么?

如果rx是v5,可以在订阅服务器上使用.unsubscribe(),但如果是v4,则必须使用.dispose()。

这似乎是唯一的问题。

答案 1 :(得分:0)

您是否重定向到构造函数中的其他页面?

基于这两页,这是在没有onInit()的情况下调用onDestroy的唯一可能性。 https://www.bennadel.com/blog/3356-ngoninit-may-not-get-called-before-ngondestroy-is-called-in-angular-4-4-6.htm

this

答案 2 :(得分:0)

我在路由中使用的组件也有类似的问题。如果将日志记录添加到构造函数中,则ngOnInit和ngOnDestroy的输出如下所示:

  • 构造函数
  • ngOnDestroy
  • 构造函数
  • ngOnInit

就我而言,问题是我如何使用<router-outlet>。简而言之,我的模板如下所示:

<div *ngIf="hasLayout()">
    <app-navigation></app-navigation>
    <ng-container *ngTemplateOutlet="routerOutlet"></ng-container>
</div>

<div *ngIf="!hasLayout()">
    <ng-container *ngTemplateOutlet="routerOutlet"></ng-container>
</div>

<ng-template #routerOutlet>
    <router-outlet></router-outlet>
</ng-template>

(由https://stackoverflow.com/a/51725607/7662651启发)

我对其进行了更改,以便我的模板中只有一个<router-outlet>组件,而没有<ng-template>。与此类似:

<div *ngIf="hasLayout()">
    <app-navigation></app-navigation>
</div>

<router-outlet></router-outlet>

此行为的原因是控制使用<router-outlet>的值的更改和异步身份验证保护的不幸组合。在我的情况下,身份验证防护人员正在等待登录初始化,并且初始化的登录会切换<router-outlet>

这是一个重现不必要行为的示例: https://stackblitz.com/edit/angular-27vrnz