通过 Angular2 路由器传递数据 [英] Passing data through Angular2 router
问题描述
我有一个组件,我可以在其中选择一组图像对象.我想将这些选定的图像传递到我的新路线 CreateAlbum.它嵌套的数据不适合作为 URL 参数传递.
I have a component where I select a set of image objects. I want to pass these selected images to my new route, CreateAlbum. The data it nested and wouldn't be suitable to pass as URL parameters.
有什么简单的方法可以实现吗?
Is there any easy way to achieve this?
这是我导航到路线的代码
Here's my code to navigate to the route
public gotoCreateAlbum(): void {
this.router.navigate([('/create-album')])
}
我选择的数据位于这个变量中
My selected data sits in this variable
@Input() selectedPhotos: IPhoto[];
这是我的路由模块
const routes: Routes = [
{ path: 'photos', component: PhotosComponent},
{ path: 'photos/:filter', component: PhotosComponent},
{ path: 'create-album', component: CreateAlbumComponent}
];
基本上我想要执行相同的操作,就好像 CreateAlbum 组件是我当前组件的子组件一样,在这种情况下我会使用 @Input()
Basically I want to perform the same operations as if the CreateAlbum component was a child to my current component in which case I would have used @Input()
推荐答案
参见 https://angular.io/指南/路由器 一个深入的例子.向下滚动到此代码片段:
See https://angular.io/guide/router for an in-depth example. Scroll down to this code snippet:
gotoHeroes(hero: Hero) {
let heroId = hero ? hero.id : null;
// Pass along the hero id if available
// so that the HeroList component can select that hero.
// Include a junk 'foo' property for fun.
this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
}
获取目标组件中 'id' 的值:
To get the value of 'id' in the target component:
ngOnInit() {
this.heroes$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) => {
// (+) before `params.get()` turns the string into a number
this.selectedId = +params.get('id');
return this.service.getHeroes();
})
);
}
这篇关于通过 Angular2 路由器传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!