Ionic 4's http.get.subscribe method fails to retain the retrieved value

I'm aware this might be a repeated question, but I haven't come across a straightforward answer yet, so here it goes.

Below is the code snippet in question:


fetchData() {
    let dataArray: Array<any> = [, , ,];
    this.prepareDataRequest().subscribe(data => {
        this.dataArray[0] = JSON.parse(JSON.stringify(data["results"]));
        this.dataArray[1] = Object.keys(JSON.parse(JSON.stringify(data["results"]))).length;
        console.log(this.dataArray[0]);
    },
    err => {
        this.dataArray[2] = `Error --> Status: ${err.status}, Message: ${err.statusText}`;
    });
    return this.dataArray;
}

prepareDataRequest() {
    const dataUrl = 'https://randomuser.me/api/?results=10&inc=gender,name,nat,email,phone,id';
    return this.http.get(dataUrl);
}

The console.log(this.dataArray[0]); line works correctly, however, the return statement appears empty. This issue seems to occur because return this.dataArray; is executed before fetching the items.

How can I resolve this? Is there a simple way to ensure everything is stored before returning? Or am I approaching this incorrectly (probably xD)?

I've experimented with async methods, but being relatively new to this, the results weren't satisfactory.

Answer №1

You've approached this the wrong way; instead, consider returning an observable:

fetchData() {
  return this.prepareDataRequest().pipe(
    pluck('results'),
    catchError(err => `Error --> Status: ${err.status}, Message: ${err.statusText}`),
  );
}

someConsumerFunction() {
  fetchData().pipe(
    // perform optional processing here
  ).subscribe(
    results => console.log(results),
    err => console.log(err),
  );
}

If you prefer to wait for completion and utilize async along with a Promise:

async fetchData() {
  try {
    const data = await this.prepareDataRequest().pipe(
      first(),
    ).toPromise();

    return data.results;
  } catch (err) {
    return `Error --> Status: ${err.status}, Message: ${err.statusText}`;
  }
}

The first method is recommended as it provides more flexibility in processing data on the consumer's end.

Answer №2

When you return your result outside of the subscribe scope, it means the dataArray has not been initialized yet.

To fix this issue, make changes to your fetchData() method like this:

  fetchData() {
    let dataArray: Array<any> = [, , ,];
    this.prepareDataRequest()
      .subscribe(data => {
          this.dataArray[0] = JSON.parse(JSON.stringify(data["results"]));
          this.dataArray[1] = Object.keys(JSON.parse(JSON.stringify(data["results"]))).length;
          console.log(this.dataArray[0]);
          // Make sure to return your dataArray here
          return this.dataArray;

        },
        err => {
          this.dataArray[2] = `Error --> Status: ${err.status}, Message: ${err.statusText}`;
        });
  }

Additionally, there seems to be confusion regarding the declaration of a local variable called dataArray when you are only using the dataArray field. It may not be necessary in that context.

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

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

"Embracing Angular2 RC6 with angular-cli: A guide to smoothly upgrading your projects' Angular2 version

After installing angular-cli on a fresh machine, I ran ng --version and received the following: angular-cli: 1.0.0-beta.10 node: 6.5.0 os: win32 x64 It appears to be the latest version according to https://www.npmjs.com/package/angular-cli. When creati ...

Creating a Powerful Application with Typescript and NodeJS

Currently, I am attempting to utilize Got with Typescript and ESM. With Got being written in Typescript itself, I anticipated a seamless integration. Alas, even after diligently following this comprehensive guide authored by the creator of Got, I am unable ...

I want to create a feature where a video will automatically play when a user clicks on a specific item in a list using Angular

Currently, I'm working on a project that involves displaying a list of videos and allowing users to play them in their browser upon clicking. The technology stack being used is Angular 2. Below is the HTML code snippet for achieving this functionalit ...

Need at least one of two methods, or both, in an abstract class

Consider the following scenario: export abstract class AbstractButton { // Must always provide this method abstract someRequiredMethod(): void; // The successor must implement one of these (or both) abstract setInnerText?(): void; abst ...

What is the correct way to interpret a JSON file using TypeScript?

Encountering Error Error TS2732: Cannot locate module '../service-account.json'. It is suggested to use the '--resolveJsonModule' flag when importing a module with a '.json' extension. import serviceAccountPlay from '../ ...

What is the best way to output a JSX element using an inline switch statement?

I have been attempting to use an inline switch in order to return an element, but all I am getting is an empty <span> </span>. What could be the issue here? getRowTdForHeader: (header: string, entry: response) => { return (< ...

Exploring the process of linking a C# REST API to an Ionic 2 mobile application

I am completely lost on how to connect an asp.net web api with my ionic 2 mobile app. Any help or advice on resolving this problem would be greatly valued! ...

Using Angular Typescript with UWP causes limitations in accessing C# WinRT component classes

Currently, I am working on a UWP application built with Angular5 and I would like to incorporate Windows Runtime Component(Universal) classes into the application to access data from a table. import { Component,OnInit } from '@angular/core'; @C ...

Add the slide number and total count in between the navigation arrows of the owl carousel

In my Angular application, I am utilizing an ngx owl carousel with specific configurations set up as follows: const carouselOptions = { items: 1, dots: false, nav: true, navText: ['<div class='nav-btn prev-slide'></div>' ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

Tips for generating cautionary claims in Playwright TypeScript assessments for non-urgent issues?

Is there a way to implement warnings instead of failures for non-critical assertions in Playwright TypeScript tests? Currently, while working on Playwright tests using TypeScript, I am searching for a solution to handle assertions that would issue warning ...

Angular Azure reports that the assets/appconfig.production.json file is missing

I am currently operating a basic single page application where the backend and frontend are hosted separately on Azure. I have "assets": [ "src/assets", "src/favicon.ico", "src/we ...

What steps can be taken to resolve the error involving the preflight request failing to pass the access control check?

I'm currently working with angular code in one VM and node code in another. I am trying to make an API call from the angular VM to the node VM, and I have already included the cors module. However, when making the API call, I keep encountering the fol ...

What is the best way to define a function agreement in Typescript?

I have created a function that can return `undefined` only when its argument is also `undefined`, otherwise it will always return a value derived from the argument provided. Here's an example of how the function works: function triple(value?: number) ...

Developing a REST API for a component with 18 interconnected elements

Currently, I am developing a REST API to expose a table to an Angular frontend, and I've encountered a unique challenge: The data required for display is spread across 10 different tables besides the main entity (referred to as "Ticket"). Retrieving t ...

Storing data locally in Angular applications within the client-side environment

As I delve into Angular and TypeScript, I've encountered a perplexing issue. Let's say I have two classes - Employee and Department. On the server-side, I've established a Many-To-One relationship between these entities using Sequelize: db. ...

Adding and Removing Classes from Dynamically Added DOM Elements in Angular 2/4

I'm currently working on creating a unique list, similar to the notification system seen on platforms like Facebook. The list is pulled in via JSON and displayed on the UI using ngFor. Each item in the list has a default CSS class called "unread", whi ...

Create a TypeScript interface that represents an object type

I have a Data Structure, and I am looking to create an interface for it. This is how it looks: const TransitReport: { title: string; client: string; data: { overdueReviews: number; outstandingCovenantBreaches ...

Dockerized Angular CLI app experiencing issues with hot reload functionality

My existing angular cli application has been dockerized with the following setup: Dockerfile at root level: # Create a new image from the base nodejs 7 image. FROM node:7 # Create the target directory in the imahge RUN mkdir -p /usr/src/app # Set the cr ...