GET calls with Ionic 2 promise


#1

Within ionic 2 Promise i’ve getting data from server like below 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);
        });
    });
  }

}

And in 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.';
      }
    });
  }
}

With the code above, I get an array containing the data, all data are the same. Same title, content, thumbnail image and everything.

Any suggestion about that ? and how i can resolve this issue ?


#2

You’re always logging the same data object data.length times.