角2+ ngOnInit()如果路由器从自身定位到当前路径(使用新查询参数)
在我home.component.ts不会被调用,我ngOnInit
:角2+ 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来尝试它。
嘿@DeborahK,终于抓到你的计算器:)再爱你的答案不亚于你对角2.感谢pluralsight课程! – rahulserver
谢谢!你看过路由课程吗? – DeborahK
还没有,但值得一看。我一定会看看! – rahulserver
你不能调用this.ngOnInit,因为它在初始化组件时只会自动调用一次,你可以通过解析它来创建你的函数并调用它。 – aimprogman
https://medium.com/@juliapassynkova/angular-2-component-reuse-strategy-9f3ddfab23f5 –