通过服务将父路线参数传递给孩子

时间:2017-02-16 17:03:06

标签: angular angular-routing

我正在尝试使用Angular团队目前推荐的方法将路径参数从父组件传递到子组件:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

父级能够成功订阅正确发出的服务。但是,在加载页面时,孩子不会收到任何内容。

服务

@Injectable()
export class AbcService {
  public paramSource: Subject<any> = new Subject<any>();
  public getParams(params) {
    this.paramSource.next(params);
  }
}

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AbcService } from './abc.service';

@Component({
  providers: [AbcService],
  ...,
})

export class AbcComponent {
  constructor(
    private route: ActivatedRoute,
    private abcService: AbcService,
  ) {
    route.params.subscribe(
      (params) => abcService.getParams(params);
    );
  }
}

儿童

export class AbcChildComponent {
  constructor(private abcService: AbcService) {
      abcService.paramSource.subscribe((params) => {
          console.log(params);
      });
  }
}

2 个答案:

答案 0 :(得分:2)

我认为代码是正确的,但事件已经丢失。在你接下来打电话的时候,没有人在听主题。一种方法是使用ReplaySubject另一种方法是在ngAfterViewInit回调中调用下一个。

答案 1 :(得分:1)

因为父项和子组件中AbcService的实例不一样

请在AbcService

中声明您的parent module
@NgModule({
  imports: [
    ...
  ],
  declarations: [
    ChildComponent,
    ParentComponent
  ],
  providers: [
    AbcService
  ]
})
export default class ParentModule { }

您不再需要在父组件处声明。

@Component({
  providers: [AbcService], // <-- Remove this
  ...,
})

还有一点,我认为我们应该在ngOnInit()而不是构造函数中订阅。

  

构造函数用于简单初始化,例如将构造函数参数连接到属性。这不适合举重。我们应该能够在测试中创建一个组件,而不用担心它可能会真正起作用 - 比如调用服务器! - 在我们告诉它之前。

https://angular.io/docs/ts/latest/tutorial/toh-pt4.html#!#the-ngoninit-lifecycle-hook

我的源代码结构

|- parent.module.ts
|- parent.component.ts
|- parent.routing.ts
|- shared.service.ts
\--- child
       |- child.component.ts

parent.html

<p>Some shared information</p>
<!-- Use router to load child component -->
<router-outlet></router-outlet>
  

为什么示例有用?

我猜是因为不使用router来初始化子组件。

在我的情况下,子组件仅在路由到时才初始化。

P / s:如果您发现任何不正确的内容,请纠正我。