我有一个角度应用程序,在那里我有一个组件,需要在每个后续组件之前的两条路径上显示:
服务>列表(相同组件)>请求
楼层>列表(相同的组件)>楼层请求
当用户选择服务路线时,我希望列表组件默认显示,并且与楼层路线相同。
我会做这样的事情:
{
path: 'service',
component: serviceComponent,
children: [
{ path: 'list', component: listComponent },
]
},
但是如果选择了服务,它将如何默认为列表?
答案 0 :(得分:1)
您可以通过使用参数来实现
{path: 'service', component: ServiceComponent},
{path: 'floor', component: FloorComponent},
{path: 'list/:type', component: ListComponent}
ListComponent
要获取参数,您需要执行几个步骤。
添加此导入
import {ActivatedRoute} from '@angular/router';
将其注入constructor()
constructor(private route: ActivatedRoute) {}
并添加到constructor()
或ngOnInit()
上,在params
上订阅
this.route.params.subscribe((params) => {
console.log(params.type);
// Here you can make request based on params.type
});
URL看起来像这样http://localhost:4200/list/service
或http://localhost:4200/list/floor
或者您可以在Angular Router中将data
属性设置为route
。
{path: 'service',
component: ServiceComponent,
children: [
{path: 'list', component: ListComponent, data: {requestType: 'service'}}
]},
{path: 'floor',
component: FloorComponent,
children: [
{path: 'list', component: ListComponent, data: {requestType: 'floor'}}
]},
ListComponent
其余与第一种方法非常相似
添加此导入
import {ActivatedRoute} from '@angular/router';
将其注入constructor()
constructor(private route: ActivatedRoute) {}
唯一的区别是在这里,因为您需要订阅data
this.route.data.subscribe((data) => {
console.log(data.requestType);
//Here you can make request based on data.requestType
});
答案 1 :(得分:0)
{path: 'service',
component: serviceComponent,
children: [
{path: '', redirectTo: 'list', pathMatch: 'full'},
{path: 'list', component: listComponent}
]},
{path: 'floor',
component: floorComponent,
children: [
{path: '', redirectTo: 'list', pathMatch: 'full'},
{path: 'list', component: listComponent}
]},
我所做的只是设置通往这些组件的默认路由。它将重定向您到列表。