问题
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);
});
}
}
回答1:
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.
回答2:
Because instance of AbcService are not the same in parent and child component.
Please declare your AbcService in parent module
@NgModule({
imports: [
...
],
declarations: [
ChildComponent,
ParentComponent
],
providers: [
AbcService
]
})
export default class ParentModule { }
You don't need to declare at parent component anymore.
Parent
@Component({
providers: [AbcService], // <-- Remove this
...,
})
One more points, I think we should put subscription in ngOnInit() instead of constructor.
The constructor is for simple initializations like wiring constructor parameters to properties. It's not for heavy lifting. We should be able to create a component in a test and not worry that it might do real work — like calling a server! — before we tell it to do so.
https://angular.io/docs/ts/latest/tutorial/toh-pt4.html#!#the-ngoninit-lifecycle-hook
My source structure
|- 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>
Why example work?
I guess because of don't use router to initialize child component.
In my case, the child component only initialize when route to.
P/s: if you find anything is not correct, please correct me.
来源:https://stackoverflow.com/questions/42280325/passing-parent-route-params-to-child-via-service