Angular 通过服务将父路由参数传递给子路由参数
我正在尝试使用Angular团队目前推荐的方法将管线参数从父组件传递到子组件: 父级能够成功订阅正确发出的服务。但是,加载页面时,子级不会收到任何内容 服务Angular 通过服务将父路由参数传递给子路由参数,angular,angular-routing,Angular,Angular Routing,我正在尝试使用Angular团队目前推荐的方法将管线参数从父组件传递到子组件: 父级能够成功订阅正确发出的服务。但是,加载页面时,子级不会收到任何内容 服务 @Injectable() export class AbcService { public paramSource: Subject<any> = new Subject<any>(); public getParams(params) { this.paramSource.next(params)
@Injectable()
export class AbcService {
public paramSource: Subject<any> = new Subject<any>();
public getParams(params) {
this.paramSource.next(params);
}
}
儿童
export class AbcChildComponent {
constructor(private abcService: AbcService) {
abcService.paramSource.subscribe((params) => {
console.log(params);
});
}
}
因为在父组件和子组件中,
AbcService
的实例不相同
请在父模块
@NgModule({
imports: [
...
],
declarations: [
ChildComponent,
ParentComponent
],
providers: [
AbcService
]
})
export default class ParentModule { }
您不再需要在父组件上声明
父母亲
parent.html
一些共享信息
为什么示例有效 我猜是因为不使用路由器来初始化子组件 在我的例子中,子组件仅在路由到时初始化
p/s:如果您发现任何不正确的地方,请纠正我。我认为代码是正确的,但事件丢失了。当你打下一个电话时,没有人在听这个话题。一种方法是使用
ReplaySubject
另一种方法是在ngAfterViewInit
回调中调用next。我不明白为什么它在角度示例中有效。。。你会把parentModule放在哪里?另外,为什么把它放在ngOnInit()
而不是contstructor中更好?角度文档使用构造函数作为示例。嗯,我想我会用你们的问题更新答案。太棒了!我的发现是ReplaySubject
有效,而ngafterview检查也有效。
@NgModule({
imports: [
...
],
declarations: [
ChildComponent,
ParentComponent
],
providers: [
AbcService
]
})
export default class ParentModule { }
@Component({
providers: [AbcService], // <-- Remove this
...,
})
|- parent.module.ts
|- parent.component.ts
|- parent.routing.ts
|- shared.service.ts
\--- child
|- child.component.ts
<p>Some shared information</p>
<!-- Use router to load child component -->
<router-outlet></router-outlet>