[英]Angular onInit doesn't get called when URL param changes
I have a path structure like this: /item/:id/editItem
.我有这样的路径结构:
/item/:id/editItem
。 In the component on the URL /item
I have multiple buttons with an onclick function like this:在 URL
/item
的组件中,我有多个带有 onclick 功能的按钮,如下所示:
this.router.navigate([
'/item/' + itemID + '/editItem'
]);
In the component on the URL /editItem
I have a console log in the ngOninit that just say that it got started.在 URL
/editItem
上的组件中,我在 ngOninit 中有一个控制台日志,它只是说它开始了。
The problem is now, on the first click, I can see the console log in the console, but with every other click on other buttons no further console logs are displayed.现在的问题是,在第一次单击时,我可以在控制台中看到控制台日志,但是每隔一次单击其他按钮就不会显示更多的控制台日志。
I am currently on the URL /item/car/editItem
and get navigated with the function above to /item/house/editItem
.我目前在 URL
/item/car/editItem
,并使用上面的功能导航到/item/house/editItem
。
Does the onInit not get called because only a URL parameter changed? onInit 是否因为仅更改了 URL 参数而未被调用? Do I need to subscribe the URL and just run my ngOnInit when the URL is changed?
我需要订阅 URL 并在 URL 更改时运行我的 ngOnInit 吗?
ngOnInit()
ngOnInit()
A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked.
在默认更改检测器首次检查指令的数据绑定属性之后,并且在检查任何视图或内容子项之前立即调用的回调方法。 It is invoked only once when the directive is instantiated.
当指令被实例化时,它只被调用一次。
If you want to listen for route changes, you could add listener:如果你想监听路由变化,你可以添加监听器:
class MyClass {
constructor(private router: Router) {
router.events.subscribe((val) => {
// see also
console.log(val instanceof NavigationEnd)
});
}
}
For route changes, see: https://angular.io/guide/router#router-events路由变化见: https ://angular.io/guide/router#router-events
The ngOnInit
method is run only when the component is created. ngOnInit
方法仅在创建组件时运行。 With routes defined as you described, you should inject ActivatedRoute
and subscribe to params
(or paramMap
) change, like按照您的描述定义路线,您应该注入
ActivatedRoute
并订阅params
(或paramMap
)更改,例如
constructor(private activatedRoute: ActivatedRoute) { //...
ngOnInit() {
this.activatedRoute.params.subscribe(({ id }) => this.doSomethingWith(id));
You can reinstantiate your component, and therefore fire the OnInit hook on navigation by setting this parameter on your RouterModule while importing it in your parent module:您可以重新实例化您的组件,因此通过在您的 RouterModule 上设置此参数同时在您的父模块中导入它来触发导航上的 OnInit 挂钩:
RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.