Vikhyath Maiya
Vikhyath Maiya

Reputation: 3192

Hide part of url in angular 2/4

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

  1. Is it possible to hide the url part from being shown in the browser.I dont want to hide the full url but only "url" ie i want to show only

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

Answers (1)

Gili Yaniv
Gili Yaniv

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

Related Questions