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

typescript add some flair to the setter function

I'm attempting to enhance a setter function within a class in the following manner: export class SearchResultSortBy{ private sortByChoice; constructor() { ...} /* getters & setters */ get sortBy() { return this.sortByCh ...

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

TypeScript overload does not take into account the second choice

Here is the method signature I am working with: class CustomClass<T> { sanitize (value: unknown): ReturnType<T> sanitize (value: unknown[]): ReturnType<T>[] sanitize (value: unknown | unknown[]): ReturnType<T> | ReturnType< ...

The Angular 2 router UMD file, router.umd.js, was not found

Trying to run an Angular 2 project and implement @angular/router is proving to be a bit challenging. Everything seems to be working fine, until the moment I attempt: import { provideRouter, RouterConfig } from '@angular/router'; As it tries to ...

Issues have been reported with Angular 10's router and anchorScrolling feature when used within a div that is positioned absolutely and has overflow set

I feel like I may be doing something incorrectly, but I can't quite pinpoint the issue. Any help or pointers would be greatly appreciated. My current setup involves Angular 10 and I have activated anchorScrolling in the app-routing.module file. const ...

Issue: FlashMessagesService not provided - NullInjectorError

Utilizing Angular 2 flash messages to showcase a message when the user clicks on the logout button has been quite the challenge. Despite adding a provider in navbar.component.ts and conducting various experiments, I still encounter the same error. Outline ...

Encountering an issue following the upgrade of Angular CLI from 8 to 10

After upgrading my Angular project from version 8 to 10, I encountered an error during compilation. The specific error message is as follows: ERROR in node_modules/ngx-loading/lib/ngx-loading.module.d.ts:4:55 - error TS2314: Generic type 'ModuleWithPr ...

NGXS Alert: Unable to resolve parameters for TranslationEditorState: (?)

I'm currently implementing NGXS for state management within my Angular 9 application. I've encountered a specific issue where any attempt at dependency injection in one of the state classes results in an error message stating "Error: Can't r ...

Exploring the Contrast of Decorators in Angular 2

Having recently started learning Angular2, I have come across some concepts that are still unclear to me despite reading various posts. The high level language used in tutorials is proving to be a challenge for me to understand, so I am reaching out for ...

What is the best way to input a parameter into an https function when it is invoked from a Swift application?

Currently, integrating stripe into my app using typescript and I have the below function: exports.deleteStripeCustomer = functions.https.onCall((data, context) => { const deleted = await stripe.customers.del( "I need to add the customers ID ...

"Enhance your forms with RadixUI's beautiful designs for

New to Radix UI and styling components, I encountered difficulties while trying to adapt a JSX component to Radix UI: Utilizing Radix UI Radio Groups, I aim to style my component similar to this example from Hyper UI with grid layout showing stacked conte ...

Why is Angular.orderBy not displaying any data on the Page?

Embarking on my first Angular project with Firebase Firestore, I am excited to showcase some of the code below. I recently learned Angular and here is what I have accomplished so far: Component.html <section class="rank"> <p class=& ...

The Angular NGRX action payload seems to undergo modifications between dispatching and execution

Angular v10, NGRX v10 I am facing a perplexing issue with my Plan object and Task properties using Angular v10 and NGRX v10. Despite making updates to Task properties within my TaskService by deep cloning the Plan object and dispatching an Action to updat ...

Guidelines for creating a masterpage and details page layout in Angular 6

In my app.component.html file, I have the following code: <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> </div> <div> <p-menu [model]="items"></p-menu> </div> Below is the code ...

Delivering secure route information to paths in Angular 2

When defining my routes in the routing module, I have structured the data passing like this: const routes: Routes = [ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginCompon ...

The custom class-validator decorator in NestJS fails to retrieve the value from the parameter

In my Nestjs project, I have created a Custom ValidatorConstraint using class-validator. The purpose is to create my own decorator and apply it later on DTO classes for validations. Let's consider this route: foo/:client After a request is made, I w ...

Error: User authentication failed: username: `name` field is mandatory

While developing the backend of my app, I have integrated mongoose and Next.js. My current challenge is implementing a push function to add a new user to the database. As I am still relatively new to using mongoose, especially with typescript, I am followi ...

Is there a way to extract the current view date information from fullcalendar using Angular?

When working with HTML code... <full-calendar defaultView="dayGridMonth" [plugins]="calendarPlugins" #calendar></fullcalendar> I am wondering how to extract the date information from the #calendar element. I attempted to consult the fullcal ...

Leveraging Sessions in Angular with Spring Boot

As I try to implement a login and session management system for my library portal, I have developed backend services using Spring Boot and frontend with Angular. While exploring an example of Spring Boot + Session Management on this link: , I made some adj ...