Rxjs-从json映射到Typescript接口 [英] Rxjs - Mapping from json to typescript interface

查看:71
本文介绍了Rxjs-从json映射到Typescript接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当我一直在探索这个新空间时,我需要进行Web API调用.所有版本之间都存在很多混乱.无论如何,我发现了一些可行的方法,并且我知道最佳实践"有点过于主观.但是,我不知道是否还有一种 direct 方式可以做到这一点.

So, as I've been exploring this new space I needed to do a Web API call. Theres a lot of confusion out there between the versions of everything. Anyhow, I found something that works, and I know "best practice" is a bit too subjective. However, what I don't know is if there is a more direct way to do this.

这是我要查找的回复的格式:

Here is the format of the response I'm seeking:

export interface AuditDetail {
  updatedAt: Date;
  updatedBy: string;
}

这是服务器端模型:

[DataContract]
public class PlanHistory
{
    [Key]
    public int Id { get; set; }

    [DataMember]
    [MaxLength(50)]
    public string UpdatedBy { get; set; }

    [DataMember]
    public DateTime UpdatedAt { get; set; }
}

这是我的Angular服务:

And here is my Angular service:

getAuditDetails(planId: number, fieldName: string, fieldValue: string): Observable<AuditDetail> {
    //return of({ updatedAt: new Date(), updatedBy: "Hawchorn" }); //Tooltip displays data

    interface PlanHistory    //Created because couldn't figure out how to directly map from Json to an Audit Detail. 
    {
      UpdatedAt: Date;
      UpdatedBy: string;
    }

    this.log("Retrieving Audit Details");
    return this.http
      .get<PlanHistory>(this.webApiUrl +
        "PlanHistories?planId=" +
        planId +
        "&fieldName=" +
        fieldName +
        "%20&fieldValue=" +
        fieldValue).pipe(map((response: PlanHistory) => {
          return <AuditDetail>{ updatedAt: response.UpdatedAt, updatedBy: response.UpdatedBy };
      }));
  }

有效.但我讨厌制作该中间接口.

That works. But I hate making that intermediate interface.

那么,如何直接从JSON到 AuditDetail 做同样的事情?

So how do I do the same thing, directly from JSON to AuditDetail?

推荐答案

您希望Web API返回camelCasing输出,因此您不必更改大小写.请参见 ASP.NET Web API中的JSON和XML序列化:

You want to have the Web API return camelCasing output, so you don't have to change the casing. See JSON and XML Serialization in ASP.NET Web API:

使用驼峰式大小写JSON属性名称,而无需更改您的数据模型上,在页面上设置 CamelCasePropertyNamesContractResolver 序列化器:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

然后您的代码将变为:

getAuditDetails(planId: number, fieldName: string, fieldValue: string): Observable<AuditDetail> {
    this.log("Retrieving Audit Details");
    return this.http
        .get<AuditDetail>(`${this.webApiUrl}PlanHistories?planId=${planId}&fieldName=${fieldName}%20&fieldValue=${fieldValue}`);
}

这篇关于Rxjs-从json映射到Typescript接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆