I cannot understand why the data set by parent component is not obtained on the child component by the following approach. I have used this approach many times, but I have really no idea what the problem:
parent component:
setData() {
this.dataService.setDataSubject('test');
}
data.service:
private dataSubject = new BehaviorSubject<any>(undefined);
getDataSubject(): BehaviorSubject<any> {
return this.dataSubject;
}
setDataSubject(param: any) {
this.dataSubject.next(param);
}
child component:
testData: any;
constructor(
private dataService: DataService
) { }
ngOnInit() {
this.dataService.getDataSubject().subscribe(data => {
// <-- it is not triggered after parent's setData() method
// is called (except first page load)
debugger;
if (data) {
this.testData = data;
}
});
}
I also tried something using something like public data$: Observable<any> = this.dataSubject;
using Observable
.
Update:
Here is my module relationship:
parent.module:
imports: [
SharedModule
],
providers: []
child.module:
imports: [
SharedModule
],
providers: []
shared.module:
providers: [
DataService
]
When I update as shown above, it still does not work. However, if I move DataService
in the providers field from shared.module
to app.module
it works. But I think it should work when it is only in shared.module
as shown above. Why?