This might be a noob question, but I could find a reference on it.
I have two components placed in different places, each component uses a Service to query an endpoint and get some data (e.g. user profile).
The service returns an observable, I need the observable to be unique or at least to make a unique request.
// Service, shared across multiple components
@Injectable()
export class SomeService {
getData(): Observable<DataModel> {
return this._http.get<DataResponse>('/some-route').pipe(
map((response: DataResponse) => this.handleResponse(response)),
share() // is this right ?
);
}
}
// Component requesting data
@Component({ selector: '...', ... })
export class FirstComponent implements OnInit {
constructor(private _service: SomeService) { }
ngOnInit() {
this._service.getData().subscribe(
data => {
console.log(data);
}
);
}
}
// Another component requesting the same data
@Component({ selector: '...', ... })
export class SecondComponent implements OnInit {
constructor(private _service: SomeService) { }
ngOnInit() {
this._service.getData().subscribe(
data => {
console.log(data);
}
);
}
}
The service works and it gets the data, but the request is sent twice, I only want a single request to be sent. The components live at the same time (let say one at the top and the second at the bottom of the screen). So they make the request simultaneously.
Is there a way the service only sent one request.
And BTW, the first request has a status of 200 and the second 304.
Thanks.
UPDATE
Possible solution
So far I managed by adding a Service variable
private _observable: Observable<DataModel>;
Then when getting the data
getData(): Observable<DataModel> {
if (!this._observable) {
this._observable = this._http.get<DataResponse>('/some-route').pipe(
map((response: DataResponse) => this.handleResponse(response)),
// HERE IS THE TRICK
publishLast(),
refCount()
)
}
return this_observable;
}
The trick is using publishLast and refCount
Any better way/idea ?