【发布时间】:2016-11-03 11:15:09
【问题描述】:
我使用 ionic 2 RC0 和 promise 从 服务器 获取数据,但我的问题 我得到了 一些数据,因为承诺数据。
所以我的问题是:
如何通过每个请求承诺不同的数据来解决这个问题? 有什么建议?
我的代码:
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 读取数据,如下代码:
首页.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}}
通过上面的代码,我得到一个包含数据的数组,所有数据都是相同的。相同的标题、内容、缩略图和所有内容。
【问题讨论】:
标签: angular typescript ionic-framework ionic2