我已经使用 ionic 2 RC0
和 promise 从 server 获取数据,但是我的 problem 我在每个请求中得到 some data 因为 promise 数据 .
所以我的问题是:
how can resolve this problem with promise different data every request ? any suggestion ?
My Code:
Api.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/from';
import 'rxjs/Rx';
@Injectable()
export class Api {
storeData: any;
constructor(public http: Http) {
this.storeData = null;
}
getData(id) {
if (this.storeData) {
return Promise.resolve(this.storeData);
}
return new Promise(resolve => {
this.http.get(URL+'?id='+id)
.map(res => res.json())
.subscribe(data => {
this.storeData = data.products;
resolve(this.storeData);
});
});
}
}
在主页我已经从api读取数据,如下面的代码:
Home.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/from';
import 'rxjs/Rx';
@Injectable()
export class Home {
constructor() {}
getDataFromApi() {
let me = this;
me.api.getData(id)
.then(data => {
if (data != null) {
for (let i = 0; i < data.length; i++) {
console.log(JSON.stringify(data));
}
}else {
this.noProducts = 'There are no products matching the selection.';
}
});
}
}
示例:
如果调用 getDataFromApi(12);
返回的数据如 {{name:bla bla, title: bla bla}}
然后再用不同的 id
再次调用该函数: 10
getDataFromApi(10);
返回一些数据,如 {{name:bla bla, title: bla bla}}
使用上面的代码,我得到一个包含数据的数组,所有数据都是相同的 . 相同的 Headers ,内容,缩略图和一切 .
1 回答
这个问题与承诺无关 . 问题是,第一次调用服务时,您发出请求,然后将响应存储在
this.storeData
属性中 . 因此,如果再次调用该服务,即使使用不同的参数,也会执行以下代码行:并且请求不会发送到服务器 . 这就是服务总是返回第一个请求中获得的响应的原因 . 为了避免这种情况,只需更改服务: