繁体   English   中英

Angular多参数路由

[英]Angular route with multiple parameters

我有一个页面将由另一个具有参数化 URL 的应用程序打开。

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

在我的 component.ts 中,我有:

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
    }
  });

我也在使用路由模块:

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

当我直接使用参数打开 URL 时,它工作正常。

问题一:

我有多种语言,i18n,所以当我通过下拉菜单更改语言时,参数消失并重定向到mysite.com/language/myapplication但我需要类似sitename.com/fr/myapplication?param1=xxx&param2=xxx

问题2:

我想在每种情况下都强制“找不到页面”,除非我有带有参数的 URL

问题3:

如何将这些参数从可选转换为必需?

使用路由参数而不是查询字符串。

在路由模块中:

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

在 my-component.ts

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

如果您需要将这些参数转换为可选的,请将这些行添加到路由模块:

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

问题1:不是angular路由器的工作。 您需要使用正确的 url 语言重新加载浏览器,不要为此使用路由器,例如: location.assign(location.href.replace('/fr', '/en-US')) ;

问题 2:一个守卫,但我更喜欢直接在组件中处理这个问题,因为您可以对没有参数的场景使用相同的处理,或者参数的值无效(例如:找不到用户)

问题3:同问题2。angular路由器没有必要参数之类的东西

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM