首页 > 解决方案 > 第一次加载页面时调用 ngOnDestroy

问题描述

当我第一次加载页面时,在某些页面上它会在 ngOnDestroy 中显示取消订阅错误,因为我正在取消订阅其中的订阅。

我不确定为什么在组件的初始化时调用 ngOnDestroy。

在此处输入图像描述

在此处输入图像描述

这是我第一次加载页面时看到的错误。

我认为这是 angular2-multiselect-dropdown 的一些问题,但在其他一些组件中,它自己的 ngOnDestory 也被调用,并表示未定义取消订阅的订阅。

所以我添加了 if 条件来删除错误信息。 在此处输入图像描述

这是订阅的创建。

在此处输入图像描述 在此处输入图像描述

实际上,我认为在定义 observable 时没有任何其他问题。

那么这是角度组件生命周期的问题还是可能是 angular2-multiselect-dropdown 的问题?

我以前没有看到这个错误,也不知道我做错了什么。任何人都可以有类似的问题或帮助我吗?提前致谢。

标签: angularlifecycle

解决方案


I had a similar issue with components that i have used with routes. If i added logging to the constructor, ngOnInit and ngOnDestroy the output looked like the following:

  • constructor
  • ngOnDestroy
  • constructor
  • ngOnInit

In my case the problem was how i used <router-outlet>. Simplyfied my template looked like this:

<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>

(inspired by: https://stackoverflow.com/a/51725607/7662651)

I changed it so that i have only one <router-outlet> component without <ng-template> in my template. Similar to this:

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

<router-outlet></router-outlet>

The reason for this behavior is a unlucky combination of a change of the value that controlls which <router-outlet> is used and a async auth guard. In my case the auth guard is waiting that the login is initialized and the initialized login switches the <router-outlet>.

Here is an example that reproduces the unwanted behavior: https://stackblitz.com/edit/angular-27vrnz


推荐阅读