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!