Utilizing ionic 2 RC0
with promises to retrieve data from the server, I am facing an issue where I consistently receive the same data in every request due to the nature of promises.
Hence, my question is:
How can I tackle this problem and ensure different data is fetched with each promise request? Any insights or recommendations?
Here's 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);
});
});
}
}
In the Home Page, the data is accessed from the API using the following code:
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.';
}
});
}
}
Example :
If we call getDataFromApi(12);
it returns data like {{name:bla bla, title: bla bla}}
Then, calling the function again with a different id
such as : 10
getDataFromApi(10);
will yield some data like {{name:bla bla, title: bla bla}}
Despite the above code, I am consistently receiving an array containing identical data. The titles, content, thumbnail images, and all other details remain the same.