问题描述
我正在尝试使用 Angular 团队目前推荐的方法将路由参数从父组件传递到子组件:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service>
父级能够成功订阅正确发射的服务.然而,当页面加载时,孩子没有收到任何东西.
服务
@Injectable()导出类 AbcService {公共参数来源:主题=新主题();公共 getParams(params) {this.paramSource.next(params);}}
父母
import { Component } from '@angular/core';从@angular/router"导入{ActivatedRoute};从 './abc.service' 导入 { AbcService };@成分({提供者:[AbcService],...,})导出类 AbcComponent {构造函数(私人路线:ActivatedRoute,私人 abcService: AbcService,){route.params.subscribe((参数) =>abcService.getParams(params););}}
儿童
导出类 AbcChildComponent {构造函数(私有 abcService:AbcService){abcService.paramSource.subscribe((params) => {控制台日志(参数);});}}
我认为代码是正确的,但事件丢失了.在您下次打电话时,没有人在听主题.一种方法是使用 ReplaySubject
另一种方法是在 ngAfterViewInit
回调中调用 next.
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-service
The 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);
}
}
Parent
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);
});
}
}
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.
这篇关于通过服务将父路由参数传递给子路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!