简体   繁体   中英

Angular Typescript toString return an object

I receive a client from an http get call as so:

    getClientById(clientId): Observable<Client>{
    let params = new HttpParams().set('clientId', clientId);
    return this.httpClient.get<Client>('http://localhost:3000/clients/getClientById', { responseType: 'json', params: params });
  }

My client class look like this:

export class Client {
name= '';
familyName = '';

public toString(){
    return this.name+ " " +  this.familyName;
}

}

My problem is when I call the toString() methode I receive an [object object].

What am I doing wrong?

This is a common misconception about TypeScript. In TypeScript generic types are not visible at runtime, it means you can't make magic mappings like httpClient.get<Client> and get a Client instance. (it is possible using AST transformers + Type-checker API, but that's another subject)

You need to manually map your object, like this :

getClientById(clientId): Observable<Client>{
    let params = new HttpParams().set('clientId', clientId);

    return this.httpClient
        .get('http://localhost:3000/clients/getClientById', {
            responseType: 'json',
            params: params
         })
         .map(data =>
             // build the Client instance here, data is a plain JavaScript object
             new Client(...)
         )
}

You get [object Object] because it is the default string value value of an object .

> ({}).toString()
"[object Object]"
> String({})
"[object Object]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM