Create an array containing the data returned from the Observable<{string, number, string}[]> stream

Currently I am working on creating an Angular 9 app, and I need to return an array with my response. Within the service class, I have a method like this:

 getReport(startDate: string, endDate: string) {
    return this.http.get<ReportReport>(
      `https://localhost:44354/report?startDate=${startDate}&endDate=${endDate}`,
      this.httpOptions);
}

The object being returned is of type Report.

export interface Report {
  range: string;
  opens: number;
  closes: number;
}

I would like the getReport method to return an array structured like this:

 list= [
    {
      name: 'Opens',
      value: Report.opens,
      color: 'green',
    },
    {
      name: 'Closes',
      value: Report.closes,
      color: 'red',
    }
]

I attempted using a subscribe observable like this:

 getReport(startDate: string, endDate: string) {
     return this.http.get<ReportReport>(
      `https://localhost:44354/report?startDate=${startDate}&endDate=${endDate}`,
      this.httpOptions).subscribe(result => { return [{
        name: 'Opens',
        value: result.opens,
        color: 'green',
      },{

        name: 'Closes',
        value: result.closes,
        color: 'red',
      }]
    });
}

but it only resulted in a subscription return.

I also tried using map like so:

 getReport(startDate: string, endDate: string) {
     return this.http.get<ReportReport>(
      `https://localhost:44354/report?startDate=${startDate}&endDate=${endDate}`,
      this.httpOptions).pipe(map(result => { return [{
        name: 'Opens',
        value: result.opens,
        color: 'green',
      },{

        name: 'Closes',
        value: result.closes,
        color: 'red',
      }]
    }));
}

Unfortunately, neither subscribe nor map worked as expected. The desired output is not just Observable<{name: string; value: number color: string;}[]>, but actually {name: string; value: number color: string;}[] without an observable wrapper.

Is there a way to achieve this or how can I modify my approach?

Thank you for your assistance

Answer №1

To handle the HTTP Observable in your controller and set up the array, you can follow this approach:

Service

getStats(startDate: string, endDate: string) {
  return this.http.get<StatsData>(`https://localhost:44354/stats?startDate=${startDate}&endDate=${endDate}`, this.httpOptions);
}

Controller

public statsArray: any;

this.statsService.getStats('...', '...').subscribe(
  response => {
    this.statsArray = [
      {
         type: 'Views',
         count: result.views,
         color: 'blue',
      },
      {
         type: 'Clicks',
         count: result.clicks,
         color: 'orange',
      }
    ];
  },
  error => { // manage error }
);

Then utilize it in the template section

<ng-container *ngIf="statsArray">
  <div *ngFor="let item of statsArray"> 
    {{ item.type }}
    {{ item.count }}
    {{ item.color }}
  </div>
<ng-container>

Answer №2

Attempting to implement async/await with promises

  async fetchReport(startDate: string, endDate: string){
    return await this.http
      .get<Report>(
        `https://localhost:44354/report?startDate=${startDate}&endDate=${endDate}`,
        this.httpOptions
      )
      .toPromise();
  }
retrieveReports(startDate: string, endDate: string) {
    this.fetchReport('2020-03-20', '2020-03-26').then(response => {
      let reportList= [
       {
        name: 'Opens',
        value: response.opens,
        color: 'green',
      },
        {
        name: 'Clicks',
        value: response.clicks,
        color: 'blue',
      }];
    });

Is it possible to access the list outside of the promise? For example, if I want to return the list from my fetchReport method?

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

Using Angular's built-in dependency injection with the $resource factory allows for

Question regarding Dependency Injection on factory resource: As far as I know, the following example is the recommended approach for injecting dependencies in Angular1: angular.module('myApp').factory('Resource', Resource); Resource. ...

Executing blur event in AngularJS

Is there a way to set up an input so that when the length is equal to 5, it triggers a blur event automatically? Any tips on how to achieve this? Here is a basic concept of what I'm looking for: <input type="tel" placeholder="type here." ...

Issue with data binding click event not functioning on Chrome when used within a nested for loop

Currently, the code below is functioning properly in Internet Explorer. It involves a download link that is disabled based on a condition. However, the same code does not work in Chrome. In Chrome, the Link remains enabled and does not disable as expected ...

Unable to delete a JSON object containing an empty value

Currently, I am dealing with data retrieved from an API that includes both title and author attributes (referred to as title_1 and title_2 in this case). To streamline the process of saving data to my database, I have set a condition where an item is deeme ...

The distinction between TypeScript generics: Differences between a generic function type and the call signature of an object literal type (Type 'T' does not match type 'T')

I'm currently working on developing an RxJS operator that waits for the input operator to complete before switching to a second operator generated dynamically using switchMap. I have created two versions of the code, one that works perfectly and anoth ...

Encountered an issue while loading a pretrained JSON model in a JavaScript script within a locally hosted

At the moment, I am using TensorFlow in Python to train a model and saving it as model.json along with the BIN file in a folder named models. My goal is to develop a web application that can load this pre-trained model for prediction. However, I have been ...

The icon for the ng-bootstrap datepicker calendar is not showing up

I recently implemented a date picker using angular-cli and ng-bootstrap. The datepicker is working perfectly after installing it from npm and adding it to the main module. However, I am facing an issue with the icon not displaying properly. Check out the ...

Retrieving value from the parent scope using the conventional approach

Today I was puzzled by some unexpected behavior of AngularJS. While using console.log to log $scope, I noticed that there was no key attached to the scope named val1. However, when I used console.log($scope.val1), it returned a value as an object. After ...

Extract table information from MuiDataTable

I am having trouble retrieving the row data from MuiDataTable. When I try to set the index from the onRowSelectionChange function to a state, it causes my checkbox animation to stop working. Below is how my options are currently configured: const option ...

The Elusive Property of 'this' in Vue Component

My Vue form component, created in TypeScript, functions correctly during runtime but does not pass type-checking. An error is thrown stating that the property 'title' is not present on the enclosing object type, which makes sense since it's ...

What is the best way to send events to connected sockets using socket.io directly from my Express 4 routes?

I have a question that others have asked before, but I'm struggling to benefit from their answers due to the unique Express setup I have. Currently, I have socket.io implemented and running smoothly on my server in a simple manner. Here is how it is ...

What causes the initial array to be altered when modifying the value returned by find()?

const courses = [ {'id':101,'name':'Complete Web Development'}, {'id':102,'name':'Data Structures and Algorithms'}, {'id':103,'name':'React'} ]; let sele ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

What is the best way to set up the correct pathway for displaying the image?

I'm currently facing a challenge with displaying an image from my repository. The component's framework is stored in one library, while I'm attempting to render it in a separate repository. However, I am struggling to determine the correct p ...

Tips for integrating Less and Bootstrap in an Angular 6 project

After making changes to angular.json to use less as the styleext, I tested it by creating a component. However, now I want to incorporate Bootstrap classes into my component's css/less. I specifically want all buttons in my component to have the .mx-1 ...

Customizing Passport JS Bearer strategy for various endpoints and HTTP REST operations

I'm currently using the BearerStrategy and I am attempting to configure different strategies for each endpoint or method within the same router. After reviewing the documentation, I have not come across any references to this particular scenario othe ...

TS2403 Error: Variable 'crypto' must be of type 'Crypto' as subsequent variable declarations must have the same type - currently has type 'Crypto'

Since today, we have encountered problems deploying our project. In the drone logs during the build step, the following error is appearing: Error: node_modules/@types/node/ts4.8/crypto.d.ts:4477:13 - error TS2403: Subsequent variable declarations must hav ...

Issue encountered when AngularJS struggles to evaluate regular expression within ng-pattern

Currently, I am implementing the ng-pattern argument in an input text field to restrict input to only numeric values: <input type="text" ng-model="numericField" ng-pattern="/^[0-9]*$/" /> However, there seems to be an unusual behavior in the regex ...

Generating one-time passwords in Node.js using Speakeasy with a specified expiration period

I'm currently utilizing https://www.npmjs.com/package/speakeasy for generating OTPs, and I want the expiration time to be set at 10 minutes. Below is the code I'm using for OTP generation: const generateOtp = function generateOtp() { let to ...

What are the steps for launching an Angular, Node.js, and MySQL web application on Heroku?

My back-end server is built using Node.js (Express) with a front-end powered by Angular 4 that consumes the back-end APIs. I am using MySQL as the database for this project. The folder structure of my back-end Node.js server looks something like this: htt ...