'How do I rerun "ngOnInit()" after navigating to the same URL (parameter is different)? [duplicate]
In my app there is a URL like /organization/campaign/{campaign handle}
.
My goal is to redirect the user to a default campaign handle
when the user visits the URL with an invalid {campaign handle}
.
For example, when a user visits /organization/campaign/doesNotExist
, he should be redirected to /organization/campaign/defaultCampaign
.
So I added the following code in the ngOnInit()
method.
if (parameterIsInvalid) {
this.router.navigate(['/organization', 'campaign', defaultCampaign]);
}
However, when visting a URL like /organization/campaign/doesNotExist
, the ngOnInit()
runs only once, which should be twice to work properly:
- the 1st time
parameterIsInvalid
is true, sothis.router.navigate(['/organization', 'campaign', defaultCampaign]);
runs. - the same component is loaded once again. This time
ngOnInit()
runs again, andparameterIsInvalid
is false, so no redirecting needed and the page displays normally.
But #2 doesn't happen, which leads to the data not fetched (it is fetched in ngOnInit()
, which is not executed after the redirecting), so the page is empty due to the lack of data.
Looks like although the param in URL is different, the component doesn't reload and ngOnInit()
doesn't rerun.
I am wondering how to make it happen?
I could use window.location.reload()
, but it may not be a good practice I guess.
Thanks in advance!
Solution 1:[1]
I think you can try to navigate to root, or some other URL.
Then navigate back to your default.
The code below is not tested.
if (parameterIsInvalid) {
((urlSegment: any[]) => {
this.router.navigate(["/"]).then(() => { // return to root
this.router.navigate(urlSegment); // then navigate to target url
});
})(['/organization', 'campaign', 'defaultCampaign']);
}
I think this is not the best answer, but if there is no other alternative, you can use as workaround.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | wei |