簡體   English   中英

異步REST API請求IONIC

[英]Async REST API Request IONIC

我正在嘗試將數據從對我的REST API的請求保存到IonicStorageModule ,數據是用戶信息,例如; 姓名,電話,地址等

現在我有這個:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ServicioApiProvider {
  results:Object[];
  loading:boolean;

  constructor(public http: Http) {
    this.results = [];
    this.loading = false;

  }

  buscar(ruta) {
      let promise = new Promise((resolve, reject) => {
      this.http.get(ruta)
        .toPromise()
        .then(
            res => { // Success
            this.results = res.json();
            console.log(res.json());
            resolve();
            },
            msg => { // Error
            reject(msg);
            }
          );
      });

      console.log("Last line"); 
      return promise;
   }
}

但總是這樣: "console.log("Last line");" 在承諾之前執行。

有什么想法可以將REST API的響應保存到IonicStorageModule?

由於http.get方法是異步的,因此如果您希望在數據准備好后執行該行,請將其放在then 您也可以像這樣簡化buscar(...)方法:

buscar(ruta): Promise<any> {
    return this.http.get(ruta)
        .map(res => res.json())     // Get the body of the response
        .toPromise()                // Convert the observable into a promise
        .then(
            response => {           // Success callback

                this.results = response;
                console.log(response);

                // Since the http get is async, you need to place the logic
                // to save the data in the storage here!
                // ...
                // this.storage.set('data', JSON.stringify(response));
                // ...

                console.log("Last line"); 
            },
            error => {              // Error callback

                // TODO: Handle error
                // ...

                console.log(error);
                return error;
            });
}

編輯

我從一頁調用此方法:this.servicioApi.buscar(this.path); 之后,我想訪問保存在存儲中的數據,但是它返回null(並且對存儲變量的訪問在調用方法“ buscar”之前執行),以及是否從另一個訪問數據頁面返回JSON

讓我再次修改該方法,以返回響應:

buscar(ruta): Promise<any> {
    return this.http.get(ruta)
        .map(res => res.json())     // Get the body of the response
        .toPromise()                // Convert the observable into a promise
        .then(
            response => {           // Success callback

                this.results = response;
                console.log(response);

                // Since the http get is async, you need to place the logic
                // to save the data in the storage here!
                // ...
                // this.storage.set('data', JSON.stringify(response));
                // ...

                console.log("Last line");

                // UPDATE: return the response
                return response;


            },
            error => {              // Error callback

                // TODO: Handle error
                // ...

                console.log(error);

                // UPDATE: return null if there was an error
                return null;
            });
}

所以現在我們返回響應(如果有錯誤,則返回null )。 這為我們提供了兩種在調用該方法時獲取數據的方式:

1)從回調獲取響應

this.servicioApi.buscar(this.path).then(res => {
    if(res) {
      // Here you can use the response
      // ...
    } else {
      // Here you can do something if there was an error
      // ...
    }
});

2)從存儲中獲取響應

this.servicioApi.buscar(this.path).then(() => {
    this.storage.get('data').then(responseJson => {
      if(responseJson) {

        // Parse the response since it is a JSON
        let response = JSON.parse(responseJson);

        // Here you can use the response
        // ...
      }
    });
});

編輯二

就像提到的@Sampath一樣,您可以只使用observables (這是Angular推薦的方式),如下所示:

buscar(ruta): Observable<any> {
    return this.http.get(ruta)
        .map(res => res.json())     // Get the body of the response
        .map(response => {

                this.results = response;
                console.log(response);

                // Since the http get is async, you need to place the logic
                // to save the data in the storage here!
                // ...
                // this.storage.set('data', JSON.stringify(response));
                // ...

                return response;
            });
}

然后只需訂閱該方法:

this.servicioApi.buscar(this.path)
    .subscribe(
        res => {
          // Here you can use the response
          // ...
        },
        error => {

            // TODO: Handle error
            // ...

            console.log(error);
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM