Fabio Cardoso
Fabio Cardoso

Reputation: 1269

Angular route with multiple parameters

I have a page that will be open by another application with parameterized URL.

Ex: sitename.com/language/myapplication?param1=xxx&param2=xxx

In my component .ts I have:

this.param1= this.route.snapshot.queryParamMap.get('param1');
this.param1= this.route.snapshot.queryParamMap.get('param2');

this.router.navigate(['/myapplication'],
  {
    queryParams: {
      param1: this.param1, param2: this.param1
    }
  });

I am using routing module as well:

const routes: Routes = [
  { path: '', redirectTo: '/myapplication', pathMatch: 'full' },
  { path: 'myapplication', component: myComponent },
  { path: '**', component: PageNotFoundComponent }
];

When I open the URL directly with the parameters it works fine.

Problem 1:

I have multi language on it, i18n, so when I change language via dropdown, the parameters disappear and it redirects to mysite.com/language/myapplication but I need something like sitename.com/fr/myapplication?param1=xxx&param2=xxx

Problem 2:

I want to force "page not found" in every scenario except when I have the URL with the parameters

Problem 3:

How can I transform those parameters from optional to required?

Upvotes: 3

Views: 12274

Answers (2)

Shalom Peles
Shalom Peles

Reputation: 2632

Use route parameter instead of query string.

In the routing module:

const routes: Routes = [
  { path: '', redirectTo: '/myapplication', pathMatch: 'full' },
  { path: 'myapplication/:param1/:param2', component: myComponent },
  { path: '**', component: PageNotFoundComponent }
];

And in my-component.ts

this.param1= this.route.snapshot.paramMap.get('param1');
this.param2= this.route.snapshot.paramMap.get('param2');

If you need transform those parameters to optional add these lines to the routing module:

{ path: 'myapplication/:param1/:param2', component: myComponent },
{ path: 'myapplication/:param1', component: myComponent },
{ path: 'myapplication', component: myComponent },

Upvotes: 3

HTN
HTN

Reputation: 3594

Problem 1: It's not the job of angular router. You need to reload the browser with the right url for the language, do not use router for that, something like: location.assign(location.href.replace('/fr', '/en-US'));

Problem 2: A guard, but I prefer handling this directly in the component because you can use the same treatment for scenario without parameters, or parameter's value is not valid (e.g: user not found)

Problem 3: Same as problem 2. There is no such thing such as required parameter with angular router

Upvotes: 1

Related Questions