Mar*_*rio 3 angular-ui-router angular
我使用带有可选参数的角度。我通过导航路由到一个位置:
router.navigate(["route1"], { p1: v1 });
Run Code Online (Sandbox Code Playgroud)
我看到了位置
/路线1;p1=v1
现在我尝试导航到
/路线1;p1=v1 ;p2=v2
我搜索类似的东西
router.navigate({ p2: v2 }, relative);
Run Code Online (Sandbox Code Playgroud)
但我在寻找有效的语法时遇到问题。
要允许组件路由具有多个可选参数,请在路由模块内指定路由,如下所示:
const appRoutes: Routes = [
...
{path: 'route1',component: MyComponent}
...
];
Run Code Online (Sandbox Code Playgroud)
在您希望从中调用 MyComponent 的调用组件中,使用路由器 navigator() 方法,如下所示:
router.navigate(['route1', {p1:value1,p2:value2}]);
Run Code Online (Sandbox Code Playgroud)
其中 value1 和 value2 是调用组件中要绑定到参数 p1 和 p2 的变量。
上述内容应与路由的参数 p1、p2 或 p1 和 p2 匹配。
在 HTML 模板中,使用以下路由器链接调用上述内容:
<a [routerLink]="['/route1', {p1:value1, p2:value2}]" .. />
Run Code Online (Sandbox Code Playgroud)
路由器 URL 链接将解析为:
/route1;p1=value1;p2=value2
Run Code Online (Sandbox Code Playgroud)
路由器链接如下:
<a [routerLink]="['/route1', {p1:value1}]" .. />
Run Code Online (Sandbox Code Playgroud)
将解析为 URL:
/route1;p1=value1
Run Code Online (Sandbox Code Playgroud)
以及以下路由器链接:
<a [routerLink]="['/route1', {p2:value2}]" .. />
Run Code Online (Sandbox Code Playgroud)
将解析为 URL:
/route1;p2=value2
Run Code Online (Sandbox Code Playgroud)
注意:如果你的路由器链接中省略了括号[],那么会出现以下错误并包含参数:
Error: Cannot match any routes. URL Segment: ...
Run Code Online (Sandbox Code Playgroud)
在组件 MyComponent 中,使用 paramMap 读取参数,如下所示:
const p1 = this.route.snapshot.paramMap.get('p1');
const p2 = this.route.snapshot.paramMap.get('p2');
Run Code Online (Sandbox Code Playgroud)
路由参数 paramMap 是一个可观察对象,当在应用程序中调用相同的路由时,它可能会发生变化,因此建议在组件内订阅它,如下所示:
routingSubscription: Subscription;
constructor(private activatedRoute: ActivatedRoute,
private router: Router) { }
ngOnInit(): void {
let route = this.activatedRoute.snapshot;
let urlSegments = route['_urlSegment'].segments;
let relativePath: string = '';
urlSegments.forEach((pathSegment: UrlSegment) => {
relativePath = relativePath.concat(pathSegment.path, '/');
});
this.routingSubscription = this.activatedRoute.paramMap
.subscribe((params: ParamMap) => {
const firstParam: string = params.get('p1');
const secondParam: string = params.get('p2');
if (firstParam && !secondParam)
{
let mySecondParam: string = "2";
this.router.navigate(
[relativePath, {p1:firstParam,p2:mySecondParam}]);
}
});
}
Run Code Online (Sandbox Code Playgroud)
上面的示例将允许使用第一个参数路由到组件,然后使用原始路由的相对路径重新路由回来。这也应该在功能模块中工作。
或者,可以在不量化活动路线中的各个路径段的情况下指定相对路径。这可以使用 router.Navigate() 中的relativeTo 选项来完成。
要使用relativeTo,请导入NavigationExtras接口,如下所示:
import { NavigationExtras } from '@angular/router';
Run Code Online (Sandbox Code Playgroud)
然后我们可以指定并扩展导航,如下所示:
this.router.navigate(
[{id1:firstParam,id2:mySecondParam}],
{ relativeTo: this.activatedRoute }
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8051 次 |
| 最近记录: |