How can I ensure that a spinner is only shown during an HTTP service call and dismissed when my component receives data?
To address this issue, I implemented a cache service to store data fetched from the HTTP service for future use. However, I want to show the spinner only during the initial HTTP call and not when data is fetched from the cache.
While the service functions correctly, the spinner continues to display even when data is retrieved from the cache. Is there a way to trigger the spinner display only during HTTP calls and not when fetching cached data?
In the code snippet below, the presentLoading() method gets called in ngOnInit, so it runs every time. How can I modify it to only execute when fetching data from the cache?
ngOnInit() {
this.presentLoading();
this.CategoryCtrl();
}
CategoryCtrl() {
this.serverService.getReviewsCategory(this.id)
.subscribe((data) => {
this.category_sources = data['value'];
this.stopLoading();
});
}
async presentLoading() {
const loadingController = this.loadingController;
const loadingElement = await loadingController.create({
spinner: 'crescent',
});
return await loadingElement.present()
}
async stopLoading() {
return await this.loadingController.dismiss();
}
}
EDIT1: This is the CacheService:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CachingService {
constructor() { }
private _cache = {};
isCached(url: string) {
return this._cache[url];
}
getData(url: string) {
return this._cache[url];
}
setData(url) {
return (data) => {
if (data && (data instanceof Error) === false) {
this._cache[url] = data;
};
}
}
reset() {
this._cache = {};
}
}
This is the server service's method:
getReviewsCategory(cat_id) : Observable<any> {
if (this._c.isCached(url)) {
return of(this._c.getData(url));
}else{
var modeapp = window.sessionStorage.modeapp;
var typemodeapp = typeof(window.sessionStorage.modeapp);
if (modeapp === "online") {
let promise = new Promise ((resolve, reject) => {
this.httpNative.get(url, {}, {}).
then((data) => {
let mydata = JSON.parse(data.data);
console.log("Data from HTTP: ");
console.log(mydata);
resolve(mydata);
}, (error) => {
console.log("error in HTTP");
reject(error.error);
}
);
});
var observable = from(promise);
}
}
return observable
.pipe(
tap(this._c.setData(url))
);