profiler
profiler

Reputation: 627

Distinguish router path in Angular

Angular routing:

{
    path: ':id',
    loadChildren: () => import('./test/test.module').then(m => m.TestModule)
  },
  {
    path: '**',
    component: AnyComponent
  },
  

There is any mechanism for distinguish routing path, which are was provided from url, f.e.

I. If the User provide/enter in browser url -> http://example.com/10

- will be calling below routing

path: '**',
    component: AnyComponent

II. If in component, we are using the router navigate:

 this.router.navigate([`${this.someData.id}]);
 
 will be calling:
 
path: ':id',
loadChildren: () => import('./test/test.module').then(m => m.TestModule)

So I would like to select/control which component will be loading, according to how the proper url will be provided (By User or By Code)

Upvotes: 0

Views: 313

Answers (2)

chris burd
chris burd

Reputation: 818

this should be done on the component and you should not be doing wild card routing on the root route. this will cause you state issue on the angular router.

so what you should do is create a root component also called a parent in your lazy loaded route then call the child from there.

IE number/:id.

NOT :id - if you do this - this will create many problems for yourself because all routes will be caught by the :id route which in effect is the exact same as the catchall route **. the causation would be no matter what route the users takes unless its strong typed and placed before this route - every single route would go there so if someone went too contacts as an example it would be caught by the same route that you want the number 10 to go to.

the angular router is incredibly powerful is you use it properly - but I think for you its a logic thing, you need to reshape your routes so that they can be maintained.

in terms of the getting the end of the url from the route. I've provided an example for you.

constructor(router: Router){}

ngOnInit(){ const routeName = 
this.router.url.split('/').pop();
if(routerName==='10'){
do something here
}
}

https://angular.io/guide/router

Upvotes: 1

DeborahK
DeborahK

Reputation: 60518

AFAIK, using the code based approach leverages the same mechanism as the user-entered route. So I don't think that there is a built-in way to distinguish them.

Alternate ideas:

  1. Use different routes. For example: http:/example.com/10 and http://example.com/id/10 so that they can be captured and processed differently.

  2. Pass data to the route using something like shown here: Pass data in Angular router dynamically

Upvotes: 1

Related Questions