Currently have a scenario where a method within a shared service is used by multiple components. This method makes an HTTP call to an endpoint that will always have the same
.
class SharedService {
private savedResponse; //to return second time onwards
constructor(private http: HttpClient) {}
getSomeData(): Observable {
return new Observable((observer) => {
if (this.savedResponse) {
observer.next(this.savedResponse);
observer.complete();
} else { /* make http request & process */
this.http.get('some/endpoint').subscribe(data => {
this.savedResponse = data;
observer.next(this.savedResponse);
observer.complete();
}); /* make sure to handle http error */
}
});
}
}
You can verify singleton by placing a random number variable in the service. console.log should print the same number from everywhere!
/* singleton will have the same random number in all instances */
private random = Math.floor((Math.random() * 1000) + 1);
The advantage: This service even after this update returns observable in both cases (http or cache).
Note: Make sure the provider for this service is not added individually in each component.