父级能够成功订阅正确发出的服务.但是,加载页面后,孩子不会收到任何东西. 服务 @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); }); }}解决方案我认为代码是正确的,但是事件丢失了.在您下次拨打电话时,没有人在听主题.一种方法是使用ReplaySubject,另一种方法是在ngAfterViewInit回调中调用下一个.I am trying to pass route parameters from a parent component to child component using the method that the Angular team currently recommends: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-serviceThe parent is able to successfully subscribe to the service which does emit correctly. However, the child does not receive anything when the page is loaded.Service@Injectable()export class AbcService { public paramSource: Subject<any> = new Subject<any>(); public getParams(params) { this.paramSource.next(params); }}Parentimport { 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); ); }}Childexport class AbcChildComponent { constructor(private abcService: AbcService) { abcService.paramSource.subscribe((params) => { console.log(params); }); }} 解决方案 I think code is correct, but event was lost. At the time you call next, nobody is listening to subject. One way is to use ReplaySubject another is to call next in ngAfterViewInit callback. 这篇关于通过服务将父级路线参数传递给孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-22 05:28