I got several components subscribing to my data service and they are all working fine. But in one of my components, I try to subscribe twice (inside ngOnInit and ngAfterViewInit) but this doesn't work. Here is the component:
ngOnInit() {
this.dataService.data$.pipe(first()).subscribe(subscribeToData => {
this.title = this.dataService.getData("...");
this.anotherService.getData
.subscribe(another => {
this.data = data;
},
...
});
}
ngAfterViewInit() {
this.dataService.data$.pipe(first()).subscribe(subscribeToData => {
let options = {
data: {
}
...
{
title: this.dataService.getData("...");
},
...
};
...
});
}
If I remove subscribe from ngOnInit then ngAfterViewInit works fine, else it fails. So is there a way to subscribe two or more times from within the same component at the same time?
Here is the data service:
private dataSource = new ReplaySubject(1);
data$ = this.dataSource.asObservable();
loadData(... : void) {
if (sessionStorage["data"] == null {
this.http.request(...)
.map((response: Response) => response.json()).subscribe(data => {
...
sessionStorage.setItem("data", JSON.stringify(this.data));
this.dataSource.next(this.data);
...
});
} else {
this.dataSource.next(this.data);
}
}
getData(... : string){
...
}
ngOnInit()is the first life cycle hook - so it will always be executed first. Once you have subscribed to the observable in ngOnInit, you can store it in a variable and then use that in the ngAfterViewInit. - Nicholas K