仅在从Http服务中获取数据的情况下,如何显示微调框?

时间:2019-03-24 21:28:56

标签: javascript angular typescript http ionic-framework

我只必须在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))
        );

2 个答案:

答案 0 :(得分:1)

我可以看到您正在从服务中返回一个可观察对象,您可以尝试以下方法以查看是否有帮助。

     CategoryCtrl() {
       this.serverService.getReviewsCategory(this.id)
       .subscribe((data) => {
         this.category_sources = data['value'];
         this.stopLoading();
       },
       (error) => console.log(error),
       () => this.stopLoading(); // This always execute
     );}

文档:http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-subscribe

但是,我认为问题可能出在您调用.dismiss()的对象上  从。您应该在元素的实例而不是对象本身上调用dismiss。

let loadingElement: Loading = null;

async presentLoading() {
   const loadingController = this.loadingController;
   this.loadingElement = await loadingController.create({
     spinner: 'crescent',
   });
   return await loadingElement.present()
}

async stopLoading() {
   return await this.loadingElement.dismiss();
}

答案 1 :(得分:0)

您可以使用HttpInterceptor类来拦截所有http调用,并且在拦截方法中,可以停止并启动微调器。

广义上讲,结构为:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Start the spinner.
    return next.handle(req).pipe(
        map((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                // Stop the spinner
            }
            return event;
        })
    );