I have declared a subject in service and tried to push the response got by making a GET call to back end using "subject.next()"..also assigned an observable for the subject using "subject.asObservable()" and subscribed to the observable in two different components(parent and router outlet child). Problem is that the observable is emitting the new value for only one subscriber not for two subscribers.
Service
subject = new Subject<any>();
observable = this.subject.asObservable();
public getDetails(id) {
return this.http.get(this.url.concat(id))
.pipe(map(data => this.extractDetails(data),
catchError(err => this.handleError(err)));
}
public extractDetails(data){
this.subject.next(data);
return data;
}
parent component
ngOnInIt(){
this.hitUrl();
}
getDetails(){
this.service.observable.subscribe(
(data: any) => {
console.log(data);
},
err => {
console.error(err);
}
)
}
hitUrl(id: string) {
this.service.getDetails(id).subscribe(
(data: any) =>
if(!!data){
console.log(data);
this.getDetails();
}
},
err => {
console.log(err);
}
);
}
router-outlet child component
ngOnInIt(){
this.hitUrl();
}
getDetails(){
this.service.observable.subscribe(
(data: any) => {
console.log(data);
},
err => {
console.error(err);
}
)
}
hitUrl(id: string) {
this.service.getDetails(id).subscribe(
(data: any) =>
if(!!data){
console.log(data);
this.getDetails();
}
},ngOnInIt(){
this.hitUrl();
}
getDetails(){
this.service.observable.subscribe(
(data: any) => {
console.log(data);
},
err => {
console.error(err);
}
)
}
hitUrl(id: string) {
this.service.getDetails(id).subscribe(
(data: any) =>
if(!!data){
console.log(data);
this.getDetails();
}
},
err => {
console.log(err);
}
);
}
err => {
console.log(err);
}
);
}
In the components hitUrl() also triggers when a call to action is performed then i need that observable should emit latest data to both the subscribers(if call to action is performed from parent or router outlet child).