When retrieving objects using Angular's HttpClient, properties may be null or empty

I am working with a service class in Angular that utilizes the HttpClient to retrieve data from a web service. The web service responds with a JSON object structured like this:

{
  "id": "some type of user id",
  "name": "The name of the user",
  "permissions": [ 
    "Array of permission names as strings"
  ]
}

The goal is to have the HttpClient's get<> method return these objects typed as instances of my custom DomainUser class.

This is what the DomainUser class looks like:

export class DomainUser {
  public id: string;
  public name: string;
  public permissions: string[];

  public get isAdmin(): boolean {
    return this.permissions.includes('admin permission's name');
  }
}

However, when trying to access the value of the isAdmin property of an instance of DomainUser, it shows as undefined. How can I correctly obtain the user data typed as DomainUser?

The get call is made like this:

this.http.get<DomainUser>(this.apiUrl + '/Users/Self').subscribe(
  next => {
    console.info('User: "%s" (Admin: %s)', next.name, next.isAdmin ? 'yes' : 'no');

    // ...
  },
  error => {
    // handle errors
  }
);

Answer №1

If you are looking to convert the text into a new object, rather than a new DomainUser instance, you will need to make adjustments. Remember that methods cannot be parsed as they do not exist in this context. One way to achieve this is by following a similar approach:

this.http.get<DomainUser>(this.apiUrl + '/Users/Self')
  .map(data => Object.assign(new DomainUser(), data))
  .subscribe(response => {
      console.info('User: "%s" (Admin: %s)', response.name, response.isAdmin ? 'yes' : 'no');

    // ...
  },
  error => {
    // handle errors here
  }
);

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

Navigating the complexities of managing numerous checkboxes in React

I am a beginner with react and recently received a task to complete. The requirements are: Show multiple checkboxes. The order of checkbox names may change in the future, allowing the client to decide the display order. Display checkboxes based on their a ...

Angular List Selector: A versatile multiple selection component with a stylish list design

I'm in need of a select component similar to the one shown in https://i.sstatic.net/mo6NH.png The issue is that Material Angular doesn't have this specific component, so I opted to use the default HTML select inside my component. Everything was ...

Having trouble with VS Code on my Linux system - npm error popping up?

protons@protons-HP-EliteBook-840-G3:~/Desktop/NH_Facility_Portal_V0$ sudo npm install [sudo] password for protons: npm notice npm notice New minor version of npm available! 8.12.1 -> 8.13.2 npm notice Changelog: https://github.com/npm/cli/releases/tag ...

Updating data within rows in Angular 4

Is there a way for me to update the value in my row based on a selected ingredient from a dropdown list? I want the unit price to be patched into the input field when a specific ingredient is chosen. You can find the relevant code snippets by visiting TH ...

Discover the best way to showcase items within an arrayList using dual CSS styles!

I'm currently working on a project that involves an arrayList with two names: Bob and Steve. I have the requirement to display them in different colors, where Bob should be displayed in green and Steve in red. Component.CSS .Bob{ font-weight:bold; ...

Swapping Out Imports with Window Objects in TypeScript

After creating a TypeScript module that relies on a third-party library, the JavaScript output from compilation includes a statement using require: "use strict"; var dexie_1 = require("dexie"); var storage; (function (storage) { ... })(storage || (stora ...

Where's the tsconfig.json for Firebase Emulators?

I've encountered an issue with my Firebase project that's written in JavaScript (not TypeScript). When attempting to run the functions emulator, I'm getting the following error: $ firebase emulators:start --only functions ⚠ functions: Ca ...

Return the reference to an injected service class from the location where it was implemented

Is it feasible to return a reference from a component class with a custom interface implemented to the injected service class in my Angular 6 project? Here is an example of what I am aiming for. ServiceClass @Injectable() export class MyService { co ...

To validate any object, ensure that it contains a specific key before retrieving the corresponding value in typescript

When looking at a random object, my goal is to verify that it follows a certain structure. obj = {WHERE:{antherObject},OPTIONS{anotherObject}} Once I confirm the object has the key using hasProperty(key), how can I retrieve the value of the key? I thoug ...

Sharing information with a child component

I am currently working on creating a Github search app using the Github API, but I am facing some challenges with passing data to a child component. The goal is for the user to click on the "view profile" button, which will lead to a URL like user/userID a ...

Encountering an issue with npm packages failing to install due to an

There seems to be an issue with npm. Kindly report this error at: Error code: EINVALIDTYPE Error type: Typeerror Argument #5: Expected object but received string Error occurred in: inflatableChild (C:\Program Files\nodejs\node_mod ...

The use of dates (YYYY-MM-DD) as identifiers in HTML/Angular 2 is causing issues

I have successfully created a calendar using html in Angular 2, and now I am looking to incorporate events into it. These events should be able to color specific days, add a dot inside the cell, or something similar. I have a json file that contains the ev ...

Unable to access API hosted on localhost from Angular Client integrated with C# Backend running on a standalone server unit

I have an Angular Client (v14) and a .Net 6 WebAPI running on separate projects within a Raspberry Pi. The setup is for a standalone kiosk where both the front end and backend are hosted on the same device. My goal is to access the front end from a PC on ...

How can I ensure that reactive form fields are properly validated in Angular2?

I am currently facing issues with validating Reactive form field in Angular 2. I have implemented a custom validator for this purpose, but it seems like my approach is not yielding accurate results as some of the test cases are failing. If anyone has insig ...

Troubleshooting Angular applications in Rider

After conducting some research online, I stumbled upon a method to debug Angular apps in Rider. However, the process doesn't quite sit well with me due to its complexity for such a simple task. Thus, I am reaching out here to inquire if this approach ...

Loop through the array while handling a promise internally and ensure completion before proceeding

I am currently working on populating a response array with Firestore snapshots and creating download links for stored files within each snapshot. Despite trying various solutions involving Promises, the response array consistently ended up being null. do ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

TypeScript class featuring a unique method that is not utilized in every instance

I have a TypeScript class that is managing ZMQ bus communication. Initially, I created a general class that can be instantiated multiple times. However, now I need to create instances with slight variations that do not perfectly fit the generic class I o ...

Tips on inserting a variable into an icon class in Angular 7

I am looking to add a unique icon to each item on my page, which is being generated inside of an *ngfor loop. For example: <i class="var"></i> Instead of 'var', I want to dynamically insert a variable provided by my service class in ...

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...