Extract data from an HTTP request and assign it to variables using filter and map in Angular

I need to extract data from an http get request and assign it to 3 separate variables once fetched.

Data: [
{ 
    reportId: 1, 
    results1: [{
        name: "TotalReferralsMade",
        optionId: 3082,
        factor: 1,
        description: null
        }],
    results2: [ ],
    results3: [{
        name: "2014/15",
        dateRangeId: 469,
        dateFrom: "2014-04-01T00:00:00.000Z",
        dateTo: "2015-03-31T00:00:00.000Z"
}]}]

Above is the structure of the data that needs to be split into 3 variables. Below is the code for the http request:

public GetReportOptions (): Observable<ReportOptions[]> {
    return this._http.get('uri')
        .map((response: Response) => <ReportOptions[]>response.json())
        .do(data => console.log("Options: " + JSON.stringify(data)))
        .catch(this.handleError);
}

The service is subscribed by a component, which then fetches the data in ngOnChanges function.

getReportOptions(id: number) {
this._Service.GetReportOptions(id)
  .subscribe(options => this.results = options }, error => this.errorMessage = <any>error)
}

The retrieved data is currently stored in a single object called results. However, I would like to store them in individual objects named results1, results2, and results3. Is there a way to achieve this?

Answer №1

I find myself constantly questioning whether I am interpreting your query accurately, as it seems to be more of a Javascript/Typescript question rather than specifically related to Angular2. Assuming I have grasped the essence of your inquiry and objective, I believe this solution may address your needs.

getReportOptions(id: number) {
    this._Service.GetReportOptions(id)
           .subscribe(options => {
               //this.results = options; 
               this.results1 = options[0].results1;
               this.results2 = options[0].results2;
               this.results3 = options[0].results3;
           }}, error => this.errorMessage = <any>error)
}

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

Is it possible to apply a formatting filter or pipe dynamically within an *ngFor loop in Angular (versions 2 and 4

Here is the data Object within my component sampleData=[ { "value": "sample value with no formatter", "formatter": null, }, { "value": "1234.5678", "formatter": "number:'3.5-5'", }, { "value": "1.3495", "formatt ...

Configuration error with MultiCapabilities

Encountering an issue while utilizing multiCapabilities with two web browsers (Firefox and Chrome). Below is a snippet from my configuration: exports.config = { allScriptsTimeout: 11000, seleniumAddress: 'http://localhost:4444/wd/hub', b ...

What prevents me from employing my nestjs unique decorator within a constructor?

I am looking to develop a personalized decorator that fetches tenant information. This is the current code snippet I have: export type TenantInfo = { token: string id: string } export const TenantInfo = createParamDecorator( (data: unknown, cont ...

Ways to turn off the dragging animation for cdkDrag?

I am facing an issue with cdkDrag where a small preview of the item being dragged shows up. I want to disable this feature and remove any CSS classes related to the dragging state. Can anyone guide me on how to achieve this? As you can see in the image, t ...

The 'undefined' type cannot be assigned to the 'never' type

interface A { name?: string age: number } var a: A = { name: '', age: 23 } var result:A = (Object.keys(a) as Array<keyof A>).reduce((prev, key) => { if (a[key] || a[key] === 0) { prev[key] = a[key] // an error was reporte ...

What is the best way to fetch all Firebase database IDs using Angular?

Is there a way to fetch all data from Firebase database along with their respective IDs? Currently, I have two functions - getAll() and get(input) that retrieve specific products based on the given ID. However, my current implementation only returns obje ...

Having trouble with the clip-path in d3.js liquid fill gauge

Attempting to integrate the d3.js liquid fill gauge into my angular2 webapp has been a challenge. The clippath functionality seems to be malfunctioning, resulting in no wave being generated at all. https://i.stack.imgur.com/3Bmga.png instead of https://i. ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. Click here for image description However, we are looking to transition this functionality to an ajax or HTTP call. While w ...

Tips for adjusting the size and positioning the ng bootstrap carousel in the center

My Angular project is using ng bootstrap, but I'm facing a styling issue. The content doesn't display in the center, rather it appears in the upper left corner: example I would like the content to be centered and wide under the blue headbar. W ...

Steps for creating a copy of an Angular component

https://i.stack.imgur.com/4RMsR.png Whenever the user clicks on the Create Copy button, I aim to replicate the content of the DashboardComponent and position the duplicated version below the original one (the DashboardComponent featuring four dark blue sq ...

What is the procedure for disabling validation in the onValueChanged function within Angular?

Is there a way to disable validation in the onValueChanged function in Angular? Check out this demo I have a form where I change the device value upon completion. However, every time I click on the device (in the onValueChanged function), it triggers the ...

What is the best way to display a Lit Element Web component within a Typescript Express application?

After creating a Typescript Express Server, I have the following files: src/server.ts import express from "express"; import { HomeController } from "./controllers"; const app: express.Application = express(); const port: number = ((proc ...

The issue of resolving custom paths imports in Typescript has been a persistent challenge for developers

Currently, I am developing a project in PHP and utilizing Typescript. I aim to follow a monorepo pattern similar to what NX offers. However, I am facing challenges when attempting to compile typescript for each of my apps. Here is the current structure of ...

Navigating routes for a module sourced from NPM: Best practices

Looking for guidance on loading Angular routes from an NPM module? Take a look at this snippet from my app.module.ts file: import { HelloWorldModule } from 'hello-world-app-npm/hello-world-app.umd.js'; // Loading module from NPM const routes = ...

Update the data in a table using Angular

I am currently displaying an array in a table, but I need to make edits to all the values in one specific column of the table. Here is an excerpt from my code: <tr *ngFor="let line of invoice.lines; let index = index"> <td> {{line. ...

What are the steps to incorporating a personalized component into an extension?

I am working on a TypeScript file that includes a class inheriting cc.Component. My goal is to package this file as an extension and make it easily accessible within the editor, allowing users to add it to a node with ease. What steps should I take to ac ...

Steps for incorporating moment.js into an Angular 2 project

Having trouble importing moment.js into my angular2 application despite following various guides and solutions provided. Even though the package is present in my IDE (Visual Studio) and the moment.d.ts file is easily found, I keep encountering errors when ...

Is it possible for moduleNameMapper to exclude imports made by a module located within node_modules directory?

I am trying to figure out how to make my moduleNameMapper ignore imports from the node_modules directory. The issue is that one of the dependencies, @sendgrid/mail, uses imports starting with ./src/ which causes problems when importing into Jest. My curre ...

Unit testing in Angular 2: Triggering hover events

In my setup, I have a template for a specific component (MyCmp) that looks like this <template ngFor let-r [ngForOf]="range" let-index="index"> <span>{{ index < 5 ? 'Y' : 'N' }}, {{r.data}}</span> <i (mousee ...

Electron Searching for Files in Main Directory

We have developed a web application using Angular 2, but we are facing an issue when trying to run it as an Electron application. After branching out the solution and making changes to package.json to launch Electron on start, we encountered an unexpected ...