Angular: How to map JSON result from HttpClient request to class instances?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 14:44:55

问题


I have the following code which seems wrong:

public search(searchString: string): Observable<Array<ClientSearchResult>> {
    let params = new HttpParams().set('searchString', searchString);

    return this.http
        .get<Array<ClientSearchResult>>(this.searchUrl, { params: params })
        .map((results: ClientSearchResult[]) => results.map((r: ClientSearchResult) => new ClientSearchResult(r)));
}

I know that the API is returning a JSON object which is not the same as an instance of my TypeScript class. However, I want to use properties defined in the TypeScript class.

Is there a better way to map the array coming from my API call to an array that actually consists of instances of ClientSearchResult?

Here is the ClientSearchResult object:

import { Name } from './name';

export class ClientSearchResult {
    public id: string;
    public name: Name;
    public dateOfBirth: Date;
    public socialSecurityNumber: string;

    public get summary(): string {
        let result: string = `${this.name}`;

        if (this.dateOfBirth)
            result += ` | ${this.dateOfBirth.toLocaleDateString()}`;

        return result;
    }

    constructor(source: ClientSearchResult) {
        this.id = source.id;
        this.name = new Name(source.name);
        this.dateOfBirth = source.dateOfBirth? new Date(source.dateOfBirth) : undefined;
        this.socialSecurityNumber = source.socialSecurityNumber;
    }

    public toString(): string {
        return this.summary;
    }
}

回答1:


We use a wonderful library to map json to typescript objects. https://github.com/shakilsiraj/json-object-mapper

json-object-mapper depends on reflect-metadata library as it is using decorators to serialize and deserialize the data.




回答2:


As an option you may try TypeScript as operator to cast your API response to the ClientSearchResult type.

import { Http, Response } from '@angular/http';

public search(searchString: string): Observable<ClientSearchResult[]> {
    const params = new HttpParams().set('searchString', searchString);
    return this.http.get(this.searchUrl, { params: params })
        .map((results: Response) => results.json() as ClientSearchResult[]);
}

This approach requires your model class to be used as an interface, or just to be an interface:

interface ClientSearchResult {
  id: number;
  // etc
}



回答3:


I have been using this very nice (and up-to-date at the time of posting) library:

https://www.npmjs.com/package/class-transformer

It can handle very complex cases with nested classes and more.



来源:https://stackoverflow.com/questions/46654601/angular-how-to-map-json-result-from-httpclient-request-to-class-instances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!