【问题标题】:Angular HttpClient mapping removes getters from target objectAngular HttpClient 映射从目标对象中删除 getter
【发布时间】:2018-09-06 02:21:15
【问题描述】:

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

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

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

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

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

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

如果 httpClient.post 通用方法不做 map 而只做类似 return JSON.parse(jsonResult) 之类的事情,那么它有什么大不了的?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    泛型参数仅用于在编译时键入。您通知其余代码从响应返回的对象将与Person 兼容。如果响应不包含 firstName 或 lastName 属性,除非您自己检查对象形状,否则您的代码仍然无法正常工作。如果您希望该对象具有方法或其他 getter,则必须自己实例化它。

    interface PersonResponse {
      firstName: string;
      lastName: string;
    }
    
    this.httpClient.post<Person>(url, body, headers).pipe(
      retry(ConfigurationService.apiHttpRetries),
      map(personProperties => new Person(personProperties),
    );
    

    所以你可以拥有

    class Person {
      constructor({ firstName, lastName }) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
      get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }
    }
    

    【讨论】:

    • 是否有一个选项而不是在构造函数中定义类的所有字段?,我正在寻找更通用的东西......顺便说一句,为什么 .map((result) => { return Object .assign(new type(), result); } 没效果?
    • 你是什么意思它不工作/不做伎俩?这对我来说似乎是一种不错的方式
    • Pils - Object.assign(new type(), result);也不保留其他属性和吸气剂。
    【解决方案2】:

    类构造函数中的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;
    

    【讨论】:

    • 我会检查一下,你能解释一下为什么当 Object.assign 在外面时它不起作用,就像我上面评论的例子一样?
    • Yerkon - 你能回答我的评论吗?
    • 也许你的result有什么问题
    • Yerkon - 什么应该起作用?所以我不需要使用构造函数技巧?
    • 你说得对,我更新了问题,我的结果是一个数组 httpClient.post 而不是 httpClient.post...你能建议吗?
    猜你喜欢
    • 2019-09-15
    • 2018-07-25
    • 2018-12-14
    • 2015-03-29
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    相关资源
    最近更新 更多