Angular 2+ 如果路由器从自身导航到当前路由(使用新的查询参数),则不会调用 ngOnInit()
Angular 2+ ngOnInit() not being called if router navigates to current route( with new query params) from itself
在我的home.component.ts
中,我的ngOnInit
方法是:
ngOnInit() {
console.log("ngoninitcalled");
this.activatedRoute.queryParams.subscribe((params:Params) => {
let refresh = params['refresh'];
if(refresh){
// do something refreshing
}
}
}
这是我的 customFunction
customFunction(email: string, username:string) {
// do something custom
this.router.navigate([''],{queryParams: {refresh:true}});
}
'' 路由重定向到 home.component.ts
或 HomeComponent(上面的代码段)。
在检查控制台日志时,我看到当从其他组件(通过 this.router.navigate([''], {queryParams: {refresh:true}}
)使用刷新参数调用 HomeComponent 时,会调用 ngOnInit()。但是如果它是从 HomeComponent 本身调用的(如上面的代码),则不会调用 ngOnInit()。
这是预期的行为吗?我可以在自定义函数中的 router.navigate
之后安全地调用 this.ngOnInit()
以手动调用 ngOnInit()
(假设 ngOnInit
永远不会如果 HomeComponent 从自身重定向到则调用)?
导航到具有不同参数的同一组件时,不会调用 ngOnInit 是预期的行为。
但是你应该不手动调用 ngOnInit。
每次参数更改时,订阅都会收到通知。因此每次都会执行 subscribe 方法中的代码。您不需要调用 ngOnInit。
通过在订阅中移动您的 console.log 来尝试。
在我的home.component.ts
中,我的ngOnInit
方法是:
ngOnInit() {
console.log("ngoninitcalled");
this.activatedRoute.queryParams.subscribe((params:Params) => {
let refresh = params['refresh'];
if(refresh){
// do something refreshing
}
}
}
这是我的 customFunction
customFunction(email: string, username:string) {
// do something custom
this.router.navigate([''],{queryParams: {refresh:true}});
}
'' 路由重定向到 home.component.ts
或 HomeComponent(上面的代码段)。
在检查控制台日志时,我看到当从其他组件(通过 this.router.navigate([''], {queryParams: {refresh:true}}
)使用刷新参数调用 HomeComponent 时,会调用 ngOnInit()。但是如果它是从 HomeComponent 本身调用的(如上面的代码),则不会调用 ngOnInit()。
这是预期的行为吗?我可以在自定义函数中的 router.navigate
之后安全地调用 this.ngOnInit()
以手动调用 ngOnInit()
(假设 ngOnInit
永远不会如果 HomeComponent 从自身重定向到则调用)?
导航到具有不同参数的同一组件时,不会调用 ngOnInit 是预期的行为。
但是你应该不手动调用 ngOnInit。
每次参数更改时,订阅都会收到通知。因此每次都会执行 subscribe 方法中的代码。您不需要调用 ngOnInit。
通过在订阅中移动您的 console.log 来尝试。