Receiving distinct data from server with Ionic 2 promises

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.

Answer №1

The issue here is not with promises but rather with how the service is handling requests. The first time the service is called, it sends a request and stores the response in the this.storeData property. Subsequent calls to the service do not make new requests because of this check:

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

This results in the same response being returned for every call, even if different parameters are used. To fix this, you can modify the service as follows:

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' // <- Added 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)  // Return only the .products from server response
        .toPromise(); // Use toPromise() method instead of creating a new promise
  }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I make sure that the combobox in my Ionic app is aligned with the text fields in a row?

From the image provided, it's evident that my HTML code looks like this: <ion-row> <ion-col> <ion-item> <searchable-ion-select isModal="true" name="country" valueField="code" [(ngModel)]="country" title="Country" ...

The type '{ domain: string; parent: string; }' cannot be assigned to type 'string'. Error code: ts(2322)

Hello there! I am new to TS, so thank you for taking the time to read this. The problematic line in my code is: <this.RenderPostLink domain={r.domain} parent={r.parent} /> where I encounter an error. RenderImages = (): React.ReactElement => ...

Using the TranslateService in Angular to externalize an array of strings

I am new to externalizing code. As I was working on developing a month picker in Angular, I initially had an array of months with hardcoded names in my typescript file: arr = ['Jan', 'Feb', 'Mar', 'Apr', 'May&a ...

Adjusting various angular-cli configuration files or providing input variables

My application caters to different customers, requiring personalized configurations based on their needs. I am looking for a way to customize the settings in the angular-cli.json file each time I run ng build. Is there a method to: 1) Dynamically cha ...

Preventing driver closure during test suites in Appium/Webdriverio: a step-by-step guide

Currently, I am in the process of testing a react native application with a specific test suite and test cases. The test case files I am working with are: login.ts doActionAfterLogin_A.ts Test Suite: [login.ts, doActionAfterLogin_A.ts] Issue at Hand: W ...

Adjusting the audio length in React/Typescript: A simple guide

I'm currently developing a web app with React and TypeScript. One of the components I created is called SoundEffect, which plays an mp3 file based on the type of sound passed as a prop. interface ISoundEffectProps { soundType: string, // durat ...

Angular 5 offers the capability to use mat-slide-toggle to easily display and manipulate

I am experiencing an issue with displaying data in HTML using a mat-slide-toggle. The mat-slide-toggle works correctly, but the display does not reflect whether the value is 1 (checked) or 0 (unchecked). Can anyone provide some ideas on how to resolve this ...

The Angular Library seems to be malfunctioning as it does not execute the ngOnInit

I've been following the instructions from Angular CLI 6 to create a library, which can be found here. So far, I've successfully created and built my library. It includes a Component that I'm using for the UI and has an HTML selector. @Compo ...

Steps for initiating a download for an Angular Progressive Web App

In the process of building an Angular PWA, I am interested in finding a method to display a popup notification for users who are browsing my app, prompting them to add it to their home screen. Is there a way to achieve this? ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

Instructions for a safe upgrade from ngrx version 2.0 to version 4.0

Is there a direct command to upgrade from ngrx v-2 to ngrx v4 similar to when we upgraded from Angular version 2.0 to version 4.0? I have searched extensively for such a command, but all I could find in the git repository and various blogs is this npm ins ...

"PrimeNG Dropdown: The 'Showclear' option reveals the clear icon right from

In my Angular 7 application, I've been utilizing PrimeNG's Dropdown component which has been performing well. Typically, I set the showClear property to true to display a small "x" button on the right side of the dropdown control. Clicking on thi ...

What is the best way to extract and display data from an API response object in my

{ "_metadata": { "uid": "someuid" }, "reference": [ { "locale": "en-us", ... bunch of similar key:value "close_icon_size" ...

Typescript interface requiring both properties or none at all

I possess key-value pairs that must always be presented together in a set. Essentially, if I have one key with its value A:B, then there should also be another key with its value C:D. It is permissible for the object to contain neither pair as well. (An ex ...

Creating dynamic Angular child routes with variable initial segment

Recently, I've been working on a new project to set up a blogging system. The next step in my plan is to focus on the admin section, specifically editing posts. My idea for organizing the routes is as follows: /blog - Home page /blog/:slug - Access ...

Strategies for transferring data from index.html to component.ts in Angular 4

Greetings, as a newcomer to Angular, I am seeking advice on how to link my Index.html file to component.ts. Please review the code snippet below where I have created a function called scannerOutput in my Angular index.html file which is functioning properl ...

When I utilize a component to create forms, the React component does not refresh itself

One of the components I am working with is a form handling component: import React, { useState } from "react"; export const useForm = (callback: any, initialState = {}) => { const [values, setValues] = useState(initialState); const onCha ...

Ways to turn off Typescript alerts for return statements

I'm looking to turn off this Typescript warning, as I'm developing scripts that might include return values outside of a function body: https://i.stack.imgur.com/beEyl.png For a better example, check out my github gist The compiled script will ...

Reinforced.Typings does not generate fully qualified names (FQN) for types when UseModules is set to true or false

Overview: Within my solution, I have two projects: ProjA and ProjB. In ProjA, I've defined a custom RTConfigure method to streamline the configuration process for translating C# to TypeScript using the Reinforced.Typings tool. Meanwhile, ProjB houses ...

Encountering an error in TypeScript: Attempting to define type files for a third-party library triggers the TS2709 error when attempting to use the 'Optional' namespace as a type

Currently, I'm in the process of creating type files for a third-party library called optional-js. The structure is as follows: index.js var Optional = require('./lib/optional.js'); module.exports = { empty: function empty() { ...