angular - Angular 路由器事件 NavigationEnd 未按预期触发
问题描述
我在html中有一个带有* ngIf =“alertValue”的警报,在ts中我有一个带有'if'的函数,我希望当值变为“true”时我可以激活我的警报
我试过了
html
<div *ngIf="alertValue">
<div class="alert alert-primary" role="alert">
A simple primary alert—check it out!
</div>
</div>
TS
alertValue= false;
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.showNotif(this.router.getCurrentNavigation().extras.state);
}
});
showNotif(data: any) {
console.log(data);
if (data !== undefined) {
this.alertValue= true;
console.warn(this.alertValue);
}
}
在"console.log (data);"
我很好地恢复了我的价值“你好”,在"console.warn (this.alertValue);"
我恢复了“真实”,这很好。
但是我的警报没有在 html 中激活。我试图放置一个按钮,允许将“true”传递给我的“alertValue”并且我的警报激活
所以我了解如何在功能期间激活我的警报
如果你有想法,我很感兴趣
解决方案
你得router.getCurrentNavigation().extras.state
早点打电话。由于为时已晚,因此不会触发更改。
导航已经结束ngOnInit
。试着把它放在构造函数中。
// earliest life cycle
constructor() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
// subscribing to NavigationEnd which is about to happen
}
});
}
ngOnInit(){
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
// subscribing to NavigationEnd which already ended so it's waiting
}
});
}
如果您需要更多帮助,请告诉我,但还要解释更多关于您的代码的信息,我会关注这个问题。
推荐阅读
- python - 我可以在 Python 中按第二个参数对列表进行排序吗?
- flutter - 如果文本溢出颤动如何自动换行
- laravel - 使用 laravel 在 null 上调用成员函数 getClientOriginalName()
- r - ggplot2中的每月时间序列数据
- python - 产生多个敌人并在子弹击中时获取信息
- json - 如何将 JSON 中的数据合并到 Flutter 中的小部件?
- react-native - 有没有办法改变 react-native-paper 中按钮元素的底层颜色?
- c - 将接收到的参数传递给回调函数
- collections - MFC:覆盖 CMap<> 对象的 HashKey() 的正确方法?
- javascript - 无法使用 Javascript 将 HTML 按钮元素的标题或值设置为 C 度符号