异步REST API请求IONIC

时间:2017-09-23 06:35:28

标签: angular typescript ionic2 ionic3

我试图将数据从请求保存到我的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?

1 个答案:

答案 0 :(得分:3)

由于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(和get   在调用之前执行访问存储变量   方法&#34; buscar&#34;),如果我从另一个页面访问它的数据   返回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
        // ...
      }
    });
});

编辑II

就像@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);
        });