Well you could use RXJS'S Subejct
or BehaviorSubject
to multicast the data.
Example
Better approach Would be to share a single http
request for multiple observers using shareReplay
operator and take action accordingly.
You must be aware of the fact that http
returns a cold observable and
When a cold observable
has multiple subscribers
, the whole data stream is re-emitted for each subscriber
. Each subscriber becomes independent and gets its own stream of data
To Avoid Duplication of HTTP Requests shareReplay
Operator is used.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs';
import {shareReplay,tap}from 'rxjs/operators';
@Injectable()
export class ShareService {
public response$:Observable<any>;
constructor(private httpc:HttpClient)
{
this.sendRequest();
}
public sendRequest()
{
this.response$= this.httpc.get('url').
pipe(tap(res=>{console.log('called');return res;}),shareReplay(1))
}
fetchData()
{
return this.response$;
}
}
products.component.ts:
constructor(service:ShareService)
{
service.fetchData().subscribe(result=>{
console.log(result);
})
products-create.component.ts:
constructor(service:ShareService)
{
service.fetchData().subscribe(result=>{
console.log(result);this.route.navigate(['listcomp'])
}
error=>{your logic}
)
Further Reading