Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Router: How to not display parameters in the url bar?

Tags:

angular

When I use:

  constructor(router: Router) {
    router.navigate(['page2', 123456789]);
  }

I see example.com/page2/123456789 in the address bar. Is it possible to hide it? I don't want someone to be able to enter example.com/page2 so that he/she navigates to this special page. It should only work internally with the command router.navigate(['xy', 'parameter']);

like image 743
ndsvw Avatar asked Sep 23 '17 08:09

ndsvw


2 Answers

You can skip the full url display by setting skipLocationChange member true on the router:

this.router.navigate(['/view'], { skipLocationChange: true });

Docs

like image 172
Vega Avatar answered Sep 28 '22 02:09

Vega


The param hiding with dynamic data during routing was possible with state routing in angularJS or angularjs 1.x but Angular 2+ routing doesn't allow.

The only solution would be to use service else read below.

param are not meant to be hidden but data property is. So instead of using SkipLocationChange: true one should use data property. Note data property cannot be used for dynamic content. It will be more of static data.

SkipLocationChange: true Navigates without pushing a new state into history. This mean if you are navigating from /page1 to /page2 then url will still show /page1 after navigation. This is not what author is expecting. here the expectation is to show /page2 in url but without param visible in url.

The solution is to use data property in route config for example

 path: 'product', component: ProductComponent , data: [{isProd: true}]}

then you can get the value of the data as show below

 route.snapshot.data[0]['isProd'];
like image 38
Anik Rai Avatar answered Sep 28 '22 03:09

Anik Rai