Reputation: 3192
I am using angular 4 .I have a situation where i have to route to another component by using router.navigate like following.
url="/screenpath/firstScreen"
this._router.navigate(["/path/guided/"+url]);
which will be route as
localhost:4200/path/guided/screenpath/firstScreen
Setting of url is dynamic based on the screenPath i am getting from the rest end point.Now my question is
localhost:4200/path/guided/
I know skipLocationChange will hide the url.But this hides the whole url which i dont want.
Please help.Any help is appreciated.
Upvotes: 2
Views: 3893
Reputation: 3211
You can change the url manually like this:
window.history.pushState("", "", '/path/guided/');
Keep in mind that this url will be saved in browser history so you should handle cases of user route directly to /path/guided.
Because its something you want you be general in many components I suggest you use a service for it.
service.ts:
import {NavigationEnd} from "@angular/router";
routerObservableInstance$;
constructor(private router: Router){
this.subscribeToRouteChange();
}
subscribeToRouteChange(){
this.routerObservableInstance$ = this.
.router
.events
.filter(event=>event instanceof NavigationEnd)
subscribe(event => {
if(event.urlAfterRedirects.indexOf('screenpath')!=-1){
window.history.pushState("", "", '/path/guided/');
}
}
}
onDestroy(){
this.routerObservableInstance.unsubscribe();
}
In the service you subscribe to any route change and filter out only events of type 'NavigationEnd' (Imported from @angular/router).Then you should check your router url and if it contains screenpath (Or any other string you decide) you change the route to /path/guided.
Upvotes: 1