Passing dynamic data through Angular 2 route
可以将静态数据传递给 Angular 2 路由而不在 URL 上显示。
但是我怎样才能以同样的方式传递动态数据/对象呢?
- 我假设您想为 UX 目的传递简单的数据,对吗?
您可以使用解析器。解析器返回的数据可用于路由,与路由配置上的静态 data 相同的方式是
示例见 https://angular.io/guide/router#resolve-guard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 @Injectable()
export class CrisisDetailResolve implements Resolve<Crisis> {
constructor(private cs: CrisisService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot): Promise<Crisis>|boolean {
let id = route.params[‘id’];
return this.cs.getCrisis(id).then(crisis => {
if (crisis) {
return crisis;
} else { // id not found
this.router.navigate([‘/crisis-center’]);
return false;
}
});
}
}
1
2
3
4
5
6
7
8
9
10
11 path: ”,
component: CrisisListComponent,
children: [
{
path: ‘:id’,
component: CrisisDetailComponent,
canDeactivate: [CanDeactivateGuard],
resolve: {
crisis: CrisisDetailResolve
}
},
1
2
3
4
5
6
7 ngOnInit() {
this.route.data
.subscribe((data: { crisis: Crisis }) => {
this.editName = data.crisis.name;
this.crisis = data.crisis;
});
}
最好结合前面两个答案:
- G??nter Z??chbauer 的答案包括一个自定义解析器,它是一个消息丰富器:给定一个以 /crisis/15 结尾的 URL,它将把危机的完整数据传递给 CrisisComponent。我们需要解析器,但我认为 OP 不希望在 URL 中显示任何数据。
- Tsadkan Yitbarek 的回答提出了一种用于数据存储和通信的服务(类似于 Redux/Flux 中的 Store)。他正确地认为这是矫枉过正,但我??们需要将信息存储在某个地方。
因此解决方案是将共享数据放入解析器本身:与组件不同,服务是长期存在的,并且始终只有一个实例,因此解析器中的数据是安全的:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// — CrisisDetailResolve —
// In the function body, add: private currentCrisisId: number | string set(crisisId: number | string) { // change line 5 of CrisisDetailResolve: // — In your code — |
参见关于路由的 Angular 文档
你可以做两件事
1.不推荐但使用数据作为路由器参数并通过,
1
|
{ path: ‘some:data’, component: SomeComonent }
|
并用作
1
2 |
let data = {“key”:”value”}
this.router.navigate([‘/some’, data) |
2.而不是通过路由参数传递数据(因为数据可能很大并且容易受到攻击,因为它可以被用户查看)
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Injectable()
export class SomeService { data = {}; } @Component({… private click() { |
- 你不觉得共享服务对于这么简单的对象来说是多余的吗
- 是的,我认为,但如果对象太大,我更喜欢这个。
- @tsadkanyitbarek 是 localhost:0000/home/id=2 和 localhost:0000/page1/id=2 的这些工作,其中 id 是静态数据,id 号是动态的。
您可以使用状态对象从Angular7.2传递动态数据
在组件中使用 navigateByUrl
发送任何数据
1
2 3 4 |
public product = { id:’1′, name:”Angular”};
gotoDynamic() { this.router.navigateByUrl(‘/dynamic’, { state: this.product }); } |
并使用 history.state
读取它
1
2 3 4 5 |
In dynamicComponent
ngOnInit() { |
参考:
传递动态数据
来源:https://www.codenong.com/41095349/