我正在尝试使用 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);
);
}
}
child
export class AbcChildComponent {
constructor(private abcService: AbcService) {
abcService.paramSource.subscribe((params) => {
console.log(params);
});
}
}
最佳答案
我认为代码是正确的,但事件丢失了。当您下次打电话时,没有人在听主题。一种方法是使用 ReplaySubject
另一种方法是在 ngAfterViewInit
回调中调用 next。
关于angular - 通过服务将父路由参数传递给子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42280325/