Dalibor
Dalibor

Reputation: 1572

Angular - routing rewrite url

I have a problem that seems simple, but I've searched a lot for the solution but couldn't find it, especially since lots of things changed since Angular2.

I have few special pages

/page/1

represents page about water

/page/2

represents page about fire.

Other pages are "normal" like

/contact
/about

...

In RouterModule I have:

RouterModule.forRoot([      
  {
      path: 'page/:id',
      component: PageComponent     
  },
  {
      path: 'contact',
      component: ContactComponent     
  },

So Water and Fire content are generated in PageComponent depending on id 1 or 2, respectively. (I have other dynamic data, not just water and fire)

Now I want when user enters

/water

to see the content of (without changing URL!) to

/page/1

So I have a redirection, in lack of better solution:

{ path: 'water', redirectTo: 'page/1', pathMatch: 'full' },
{ path: 'fire', redirectTo: 'page/2', pathMatch: 'full' } ...

But that results in changing URL. But what I want is when user enters

/water

I want the URL to remain that, not the redirection! (Same goes for /fire and other dynamic content pages.)

Upvotes: 1

Views: 6096

Answers (2)

Dalibor
Dalibor

Reputation: 1572

Partly based on mbojko answer (because checking id on the data observable as arieljuod suggested was too much for me), I made a following solution:

RouterModule.forRoot([      
  {
    path: 'contact',
    component: ContactComponent     
  },
  {
    path: 'water',
    component: PageComponent
  },
  {
    path: 'fire',
    component: PageComponent
  }

and then in the PageComponent:

import { Location } from '@angular/common';

...

constructor(
        private location: Location,

...

private mapPathToId(path: string): number {
    switch (path) {
        case '/water':
            return 1;
        case '/fire':
            return 2;
        ...
    }        
}

ngOnInit(): void {
    const id = this.mapPathToId(this.location.path());
    this.showContent(id);          
}

Upvotes: 0

arieljuod
arieljuod

Reputation: 15848

What about this:

RouterModule.forRoot([      
  {
    path: 'page/:id',
    component: PageComponent     
  },
  {
    path: 'contact',
    component: ContactComponent     
  },
  {
    path: 'water',
    component: PageComponent,
    data: {id: 1}
  },
  {
    path: 'fire',
    component: PageComponent,
    data: {id: 2}
  }

https://angular.io/guide/router

You'll have to modify your PageComponent a little to check if there's an id on the data observable or the id comes from the url though.

Upvotes: 4

Related Questions