通过Angular2路由器传递数据

use*_*173 18 routing typescript angular

我有一个组件,我选择一组图像对象.我想将这些选定的图像传递给我的新路径CreateAlbum.它嵌套的数据,不适合作为URL参数传递.

有没有简单的方法来实现这一目标?

这是我导航到路线的代码

  public gotoCreateAlbum(): void {
    this.router.navigate([('/create-album')])
  }
Run Code Online (Sandbox Code Playgroud)

我选择的数据位于此变量中

@Input() selectedPhotos: IPhoto[];
Run Code Online (Sandbox Code Playgroud)

这是我的路由模块

const routes: Routes = [
  { path: 'photos',  component: PhotosComponent},
  { path: 'photos/:filter', component: PhotosComponent},
  { path: 'create-album', component: CreateAlbumComponent}
];
Run Code Online (Sandbox Code Playgroud)

基本上我想执行相同的操作,就像CreateAlbum组件是我当前组件的子组件一样,在这种情况下我会使用@Input()

小智 24

我希望这会奏效.尝试使用查询参数.

 <nav>
      <a [routerLink]="['/component1']">No param</a>
      <a [routerLink]="['/component2']" [queryParams]="{ page: 99 }">Go to Page 99</a>
 </nav>
Run Code Online (Sandbox Code Playgroud)

要么

opencomponent2(pageNum) {
    this.router.navigate(['/component2'], { queryParams: { page: pageNum } });
  }
Run Code Online (Sandbox Code Playgroud)

在子组件中:

constructor(
    private route: ActivatedRoute,
    private router: Router) {}

  ngOnInit() {
    this.sub = this.route
      .queryParams
      .subscribe(params => {
        // Defaults to 0 if no query param provided.
        this.page = +params['page'] || 0;
      });
  }
Run Code Online (Sandbox Code Playgroud)

我在rangle.io网站上研究了这个.试试这个,如果它适合你.否则https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service是唯一的选择.


Phi*_*ber 9

有关详细示例,请参阅https://angular.io/guide/router.向下滚动到此代码段:

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' }]);
}
Run Code Online (Sandbox Code Playgroud)

要在目标组件中获取'id'的值:

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();
    })
  );
}
Run Code Online (Sandbox Code Playgroud)