首页 文章

如何在不使用@Output的情况下在Angular2 rc6中的子/父组件中共享params变量?

提问于
浏览
0

我需要访问发送到父组件中的子组件的Params变量 .

我有以下结构:

路由:(摘录)

{
      path: 'song',
      component: SongExerciseComponent,
      children: [
          {
              path: 'reading/:id',
              component: SongReadingComponent,
          }
      ]
  }

父组件只是一个包含导航链接的模板 . 我可以像这样访问子组件中的:id var:

ngOnInit(): void {
    this.route.params.forEach((params: Params) => {
      if (params['id'] !== undefined) {
        let id = +params['id'];

现在我需要在父组件中使用相同的变量来在父模板中使用 .

这是最有效的方法吗?分享服务? https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-and-children-communicate-via-a-service

1 回答

  • 1

    你可以创建一个共享服务或者使用 Ngrx store ,灵感来自Redux for Angular2 .

    在那里你可以读到它 - https://gist.github.com/btroncone/a6e4347326749f938510

    此解决方案的优点是您可以更改并对它们做出反应 . 此外,数据是不可变的,因此您不会错误地更改某些内容 . 如果它对您不重要,请使用服务 .

相关问题