【发布时间】:2019-03-25 13:45:23
【问题描述】:
我必须仅在 http 服务调用期间显示微调器,并在我的组件接收到数据时将其关闭。
我编写了一个小缓存服务,以便仅在第一次从 http 服务中获取数据,并在每次调用时从缓存中加载该数据,避免再次调用 http 服务。
服务按预期工作,但如果我只想在 http 调用期间而不是在从缓存中获取数据时显示微调器怎么办?
这是我的组件的代码,它在我的服务的 getReviewsCategory(this.id) 方法调用 http 服务时工作,但是当它从缓存中获取时,微调器永远不会被关闭。 数据在后台以正确的方式加载,但微调器继续运行。
presentLoading() 方法在 ngOnInit 中,所以每次都会调用它,如果我只想在从缓存中获取数据时调用它怎么办?我的组件怎么会知道它?
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:这是 CacheService:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CachingService {
constructor() { }
private _cache = {};
isCashed(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 = {};
}
}
这是服务器服务的方法:
getReviewsCategory(cat_id) : Observable<any> {
if (this._c.isCashed(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))
);
【问题讨论】:
标签: javascript angular typescript http ionic-framework