angular - 第一次加载页面时调用 ngOnDestroy
问题描述
当我第一次加载页面时,在某些页面上它会在 ngOnDestroy 中显示取消订阅错误,因为我正在取消订阅其中的订阅。
我不确定为什么在组件的初始化时调用 ngOnDestroy。
这是我第一次加载页面时看到的错误。
我认为这是 angular2-multiselect-dropdown 的一些问题,但在其他一些组件中,它自己的 ngOnDestory 也被调用,并表示未定义取消订阅的订阅。
这是订阅的创建。
实际上,我认为在定义 observable 时没有任何其他问题。
那么这是角度组件生命周期的问题还是可能是 angular2-multiselect-dropdown 的问题?
我以前没有看到这个错误,也不知道我做错了什么。任何人都可以有类似的问题或帮助我吗?提前致谢。
解决方案
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
推荐阅读
- android - 如何避免在相当简单的 android 应用程序中使用 Multidex?
- javafx - JavaFX bean 是否需要可序列化?
- python - 使用 Python 附加到 Json 对象
- r - ggplot:没有 group_by() 和 summarise() 的每个时间单位(例如一个小时)的总和
- javascript - 试图在表中显示 sparql 查询
- java - 自定义“RelyingPartyRegistrationRepository”实现
- spring-boot - Spring Boot i18n + Thymeleaf:在 messages.properties 文件中使用数组
- r - R中的Epanechnikov函数等价
- python-3.x - 有没有办法将 pandas 中块的大小定义为可用内存的函数?
- html - 后 div 块滚动最前面的 div