首页 文章

Ionic 2承诺来自服务器的不同数据

提问于
浏览
2

我已经使用 ionic 2 RC0promiseserver 获取数据,但是我的 problem 我在每个请求中得到 some data 因为 promise 数据 .

所以我的问题是:

how can resolve this problem with promise different data every requestany 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 回答

  • 1

    这个问题与承诺无关 . 问题是,第一次调用服务时,您发出请求,然后将响应存储在 this.storeData 属性中 . 因此,如果再次调用该服务,即使使用不同的参数,也会执行以下代码行:

    if (this.storeData) {
      return Promise.resolve(this.storeData);
    }
    

    并且请求不会发送到服务器 . 这就是服务总是返回第一个请求中获得的响应的原因 . 为了避免这种情况,只需更改服务:

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/observable/from';
    import 'rxjs/add/operator/toPromise' // <- I've added this import!!
    import 'rxjs/Rx';
    
    @Injectable()
    export class Api {
    
      constructor(public http: Http) {
      }
    
      getData(id) {
          return this.http.get(URL+'?id='+id)
            .map(res => res.json())
            .map(data => data.products)  // You only return the .products from the server response right?
            .toPromise(); // <- you don't need to create a new promise, use the toPromise() method instead
      }
    
    }
    

相关问题