Search code examples
angularionic-frameworkangular-httpclient

Cannot convert HttpClient response to object array


How can I cast or convert an HttpClient response to array of custom class objects in Angular?

I have a provider like:

import { Client } from '../../models/client.model';

@Injectable()
export class ClientProvider {

  clients: Client[] = [];
  url = "link/to/api/clients" //Should return an array of clients

  constructor(public http: HttpClient){ }

  getClient() {
     this.http.get(this.url)
  .subscribe(
      (response) => {
        this.clients = response as Client[];
        console.log(this.clients[0]) // this works and shows the client info
        console.log(this.clients[0].getName()); //this gives error (1)
       });
  }

Error:

ERROR TypeError: _this.clients[0].getName is not a function

I even tried

(response: Client[]) => {
   this.clients = response ...}}

But it gives me the same error.

my model definition is like:

export class Client{
    id: number;
    name: string;

    getName() {
    return this.name;
    }
}

Solution

  • Issue

    The issue with your approach is, you are trying to assign the response to Client[] array. However it just the assignment of response data to client variable.

    Fix

    If you want to convert response to respective models class then you need to handle it from the model class itself.

    ex :

    Create the constructor in the model class

    export class Client{

    constructor(obj?: any) {
       Object.assign(this, obj);
    }
    
    id: number;
    name: string;
    
    getName() {
    return this.name;
    }
    

    }

    getClient() {
         this.http.get(this.url)
      .subscribe(
          (response) => {
            let clients = this.response.map(item=>new Client(item)); //Create new instance of client and set the properties.
           });
    

    Note : Check the type of response. The above implementation when the response contains the multiple client.