pinki
pinki

Reputation: 912

Properties are undefined, when getting objects via Angular's HttpClient

I have a service class, that uses Angular's HttpClient to get data from a web service. The web service returns a JSON object like this:

{
  "id": "some kind of user id",
  "name": "The user's name",
  "permissions": [ 
    "String array with different permission names"
  ]
}

I want the HttpClient's get<> method to get me these objects typed as my own DomainUser class object.

This is the DomainUser class:

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

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

When I want to get the value of the DomainUser's isAdmin property, I get the message, that isAdmin is undefined. How can I get the user data correctly typed as DomainUser?

The get call is

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

    // ...
  },
  error => {
    // error handling
  }
);

Upvotes: 0

Views: 787

Answers (1)

Robin Dijkhof
Robin Dijkhof

Reputation: 19298

You are parsing the text to a new object, not to a new DomainUser. You can't parse a method so the method does not exist. You could do something like this:

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

    // ...
  },
  error => {
    // error handling
  }
);

Upvotes: 2

Related Questions