Using Angular to transform a JSON GET response into a class with methods

Essentially, I am working with an Angular component that has a variable called DashboardConfiguration which is set to an Observable. This Observable is obtained from a resolver that utilizes a service to make a GET request for a JSON object.

The issue lies in the fact that the Observable is supplying the variable with a plain Object instead of a DashboardConfiguration object. As a result, I am unable to invoke a function of the DashboardConfiguration.

I have modeled my structure very similarly to this example which includes all code at the end of the article.

The specific DashboardConfiguration class that I need the JSON to be cast to:

export class DashboardConfiguration {
  id:string;
  createdDate?:any;
  properties?:any;
  widgets:WidgetConfiguration[];

  //This function is not being accessed
  public getWidgetByAlias(alias:string):WidgetConfiguration {
    this.widgets.forEach(function (widget) {

      if(widget.hasAlias(alias)){
        console.log("returning widget "+widget.id);
        return widget;
      }
    });
    return null;
  }
}

The HTTP GET response:

  "dashboard": {
      "id":"029c2322-8345-4eed-ac9e-8505042967ec",
      "createdDate": "",
      "properties": {
        //omitted form stackoverflow post},
      },
      "widgets":[
        {
          "id": "705c0853-e820-4c26-bc4c-e32bd7cb054c",
          "createdDate": "",
          "properties": {
            "aliases":[
              "test"
            ]
          }
        },
        {
          "id": "b5e161dd-e85e-44d4-9188-5f4d772d9b40",
          "createdDate": "",
          "properties": {
            "aliases":[
              "test1"
            ]
          }
        }
      ]
  }

The Angular component:

export class DashboardComponent implements OnInit {

  configuration:DashboardConfiguration;

  constructor(private route:ActivatedRoute) { }

  ngOnInit() {
    this.configuration = this.route.snapshot.data['dashboard'];
    console.log(this.configuration.id);
  }

  //The function that calls the non-working function!
  getWidgetByAlias(alias:string):WidgetConfiguration {
    return this.configuration.getWidgetByAlias(alias);
  }

}

The service responsible for the HTTP request:

constructor(private http:HttpClient) {}

getConfiguration(uuid:string):Observable<DashboardConfiguration> {
  return this.http.get<DashboardConfiguration>('/api/dashboard',{params: {id: uuid}});
}

The resolver:

constructor(private dashboardService:DashboardService){}

resolve(route: ActivatedRouteSnapshot): Observable<DashboardConfiguration> {
  return this.dashboardService.getConfiguration(route.queryParams['id']); //this calls the above service
}

Answer №1

If you want to merge JSON data with a newly created object, one approach is using the map operator. This method comes in handy when you need to work with API response data and add functionality to it.

By utilizing the map operator, you can achieve this by:

this.http.get<DashboardConfiguration>('/api/dashboard',{params: {id: uuid}})
  .map(result => Object.assign(new DashboardConfiguration(),result));

Learn more about Object.assign() here.

Answer №2

In this case, the HttpClient service will not automatically convert the JavaScript object into an actual instance of your class for you. Instead, it returns a JavaScript object with your class properties that you will need to handle yourself.

To achieve what you want, you'll have to write custom code to create objects of the correct type from the returned data.

If you're looking for an example of how to do this, there is one provided in this link: Angular2. Map http response to concrete object instance

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

Reference error in Angular 2 typings is not defined

My current challenge involves integrating a 3rd party module into my application using webpack. Here is how I have tried to do it: //package.json "dependencies": { "jsrsasign": "6.1.4" } //custom-typings.d.ts declare module KJUR { module jws ...

There seems to be an issue with the functionality of Angular's updateValueAndValidity() method

I am facing an issue with a simple form setup: <form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate> <input type="radio" id="enabled" formControlName="enabled" [value]="true" ...

What is the best way to send requests to an API server without directly specifying the URL in the code?

As I work on implementing an app using Angular 2, I find myself needing to make requests to my API server. However, hardcoding the full URL in every request doesn't seem like a good idea since it's likely to change. While researching a solution, ...

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...

Resetting a Subject entity

Is there a way to reset an Observable object? I'm not sure if "reinitialize" is the right term, but essentially what I want is to update the data without creating a new Observable object or new subscriptions. I want existing subscriptions to seamless ...

How can a date range validation be implemented with two distinct ngx date picker fields in Angular 10?

Click here to view the image description In the illustration provided, I am seeking a solution to restrict users from selecting dates in the end date picker that occur before the chosen start date. ...

Methods cannot be called on TypeScript primitive strings

In my exploration of TypeScript, I came across the concept that the string primitive type does not have any methods and is simply a value. To utilize methods such as toLowerCase(), one must work with the String type instead. Curious about this distinction ...

Refreshing Custom Functions within Excel Add-On - Web Edition

Currently, I am working on an Excel Add-In that includes custom functions utilizing the Javascript API. I have been following a particular tutorial for guidance. While attempting to debug using the Web version of Excel due to its superior logging capabili ...

What is the best way to arrange items by utilizing the Array index in JavaScript?

Currently, I am attempting to make the elements within this angular component cascade upon loading. The goal is to have them appear in a specific layout as shown in the accompanying image. I'm seeking guidance on how to write a function in the TypeSc ...

Angular2 Date Picker Validation: Ensuring Proper Date Selection

I have implemented a custom directive for a date picker in my project. Below is the code snippet of the template: <div class="input-group"> <input type="text" id="tbxDate" pattern="\d{1,2}/\d{1,2}/\d{4}" ...

The world of TypeScript generics and derived data types

I'm looking to streamline the process of calling multiple functions by creating a function that handles this task. These functions all require similar business logic and cleanup operations. function foo(arg: number) { // perform actions using arg ...

Securing Angular CLI Assets: Implementing canActivate for Protection

I am facing an issue where anyone can access my website's assets using URLs like http://localhost:4200/assets/filename.pdf, even when the user is not logged in. How can I secure these assets by implementing a canActivate guard? An ideal solution woul ...

Mobile-friendly Angular 2 material tables for optimal viewing on all devices

I'm currently in the process of incorporating datatables into my Angular 4 project using Angular Material datatables (https://material.angular.io/). Everything appears to be functioning properly UNTIL I switch to a mobile view, at which point the ent ...

Populate choices in the mat-select dropdown

I am encountering an issue with two-way binding in the mat-select component from Angular Material. In my TypeScript file, I have an option list and a variable for binding called valueFromDB. When I choose a value in the mat-select component, it automatical ...

using the ts-migrate-mongoose package for migrating MongoDB

I'm currently working on a NestJS application and using ts-migrate-mongoose for database migration. The issue I'm facing is related to importing a user schema from outside of the migration folder (which is located in the root folder by default). ...

ng2 Dragula and the magic of Angular pipes

I have successfully implemented Dragula to make a table of values from a database sortable. Everything functions as intended, with the ability to drag and drop table rows. However, I encounter an issue when I apply a custom pipe to three of the cell values ...

Determining the instance type of a TypeScript singleton class

I have a unique singleton implementation: class UniqueSingleton { private static instance: UniqueSingleton; private constructor() { // Only allows instantiation within the class } public static getInstance(): UniqueSingleton { if (!Unique ...

The Angular Property Decorator ensures that only one instance of a property is created per Class Type

I have implemented a Property Decorator that creates an Observable with static getter/setter for each property. Usage of the decorator looks like this: class Test { @ObservableProperty(DEFAULT_CATS) cats: number; @ObservableProperty(DEFAULT ...

Switch the icon in Angular 2 while using ngFor loop

One issue I am facing with my angular2 project is that the icon does not appear when the page loads, but only after clicking. The array being used is called "keys". <ion-grid class="dueD-line" *ngFor="let line of keys; let i=index"> <div style= ...

Node.js and Typescript encountering issues resolving module paths

I am brand new to both Express and Typescript. I recently inherited a project that utilizes express for an API. I need to make some modifications, but I am having trouble transpiling the code. I have exhausted all my options and now I'm seeking help h ...