Ionic - Async Http Calls and Ionic LoadingController Issue

i would like to have some help about using Ionic LoadingController while having multiple http calls which are processed in an async function.

Firstly, this is my async function with promises

LoadDatafromUrls(urLs) {
    return new Promise((resolve, reject) => {
      let loader = this.loadingCtrl.create({
        content: 'Info retrieving',
      });
      var urlCalls = [];
      urLs.forEach((entry: any) => {
        loader.present().then(()=>{
          this.http.get(entry.url).map((response : Response)=>{
            console.log(response.json());
            urlCalls.push(response.json());
          }).subscribe(()=>{
            console.log("subscribe");
            loader.dismiss();
          });
          
        })
      })
      Promise.resolve(urlCalls).then((res)=>{
        console.log(res);
        resolve(res);
      },
      (res)=>{
        reject(res);
      })
      //return Promise;
    })
  }

Secondly, this is the way i call the above function.

RequestObject.LoadDatafromUrls(urLs).then((results)=>{
        console.log(results);
      },
      (errors)=>{
        console.log(errors);
      })

In this method, i am having the error message below :

Error message: “Uncaught (in promise): removeView was not found” .
Moreover, it does not work in the way i am expecting.

I am really open for compeletely new methods, new ways. Please share if i can have any better implementation.

1 Like

Whatever you do, the most important thing is to always follow this exact lifecycle for loading controllers: create, present, dismiss. You are presenting and dismissing the same one multiple times, which is deadly.

Stylistically, I would recommend using forkJoin to combine all the requests into a single Observable, and use that to manage the loading controller. Do not do anything with Promises here.

I actually built a LoadingControllerHandler provider, which accepts requests to show a loading message and makes sure that no message shows if the async call completes in less than X milliseconds, ensures at most one loading message is visible at a time, etc. I expanded on code @rapropos posted in this forum, so there you go. But I did this because I might have multiple providers making async calls at the same time, depending on when things resolve, connection issues, etc. If all the loading messages are in the same method and page, then use Observable.forkJoin. Also, I would create a separate variable or method that forkJoins those Observables, and have that method return a single Observable. Keeps your code more clean and modular.