我正在尝试将来自对 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");"
在 promise 之前执行。
有什么想法可以将 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;
});
}
编辑
I'm calling this method from one page:this.servicioApi.buscar(this.path); After that I want to access to the data that I saved in storage, but it returns null (And the get to access to the storage variable executes before the call to the method "buscar"), and if I access to the data from another page it returns the 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);
});
关于angular - 异步 REST API 请求 IONIC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46376796/