本文介绍了Angular HttpClient映射从目标对象中删除吸气剂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HttpClient从API中获取Json,并使用该HttpClient的自动映射将json映射到目标对象,如下所示:

I am using HttpClient to get Json from the API and using the autoMapping of that HttpClient to map the json to the target object like this:

this.httpClient.post<Person>(url, body, { headers: headers, params: httpParams }).retry(ConfigurationService.apiHttpRetries)

我的问题是我的Person类包含如下的吸气剂:

My problem is that my Person class contains getters like:

get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }

在httpClient.Post之后,我得到一个Person对象,该对象仅包含从json返回的字段,不包含其他属性,并且没有我的FullName getter.

after httpClient.Post, i am getting a Person object that contains only the fields that returned from the json and not other properties and without my FullName getter.

我尝试使用Object.Assign,但它也无法正常工作...

I tried to use Object.Assign but it also not working...

如果httpClient.post通用方法不执行映射,而仅执行return JSON.parse(jsonResult)之类的事情,那么有什么大用处?

What is the big deal of the httpClient.post generic method if its not doing map and only doing something like return JSON.parse(jsonResult)?

推荐答案

Object.assign()在类构造函数中:

 class Person {
     firstName: string;
     lastName: string;;
         constructor(data: Object|Person) {
            Object.assign(this,data);
         }
      get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }
    }

    ...

        this.httpClient.post<Person>(url, body, headers).pipe(
              retry(ConfigurationService.apiHttpRetries),
              map(personProperties => new Person(personProperties),
       );

不需要映射每个属性:

this.firstName = firstName;
this.lastName = lastName;

这篇关于Angular HttpClient映射从目标对象中删除吸气剂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:36