【问题标题】:Mapping Server site model to Client site model in Angular 4在Angular 4中将服务器站点模型映射到客户端站点模型
【发布时间】:2018-04-14 02:05:50
【问题描述】:

我的服务器站点 C# 模型

 public  class Teacher:Entity
 {
    public string Name { get; set; }
    public string PhoneNo { get; set; }
 }

客户站点 TypeScript 模型

export class Teacher extends Entity {
    public name:string;
    public address:string;
    public phoneNo :string;
}

客户现场服务

getDataById(id: string):Observable<T> {
    return this.repo.get(this.subUrl+'query',id).map( (res)=>{ return <T> res.json()})
}

客户端站点控制器

this.subscription= this.techerService.getDataById(this.id).subscribe( (data:Teacher) =>{
       console.log(data);
       this.model.name=data.name;
       console.log(this.model))};

输出结果:Result on browser

我可以在没有这种类型的映射的情况下进行映射吗?

this.model.name=data['Name'];

我想映射这种方法或更好的方法

this.model.name=data.name;

请帮忙

【问题讨论】:

  • 使用 TypeScript interface,而不是 class。在您的后端,设置JsonSerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
  • config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;解决了这个问题

标签: angular typescript


【解决方案1】:

您对Teacher 的声明有一个小写的name。您收到一个带有大写 Name 的对象。 TypeScript 应该抱怨data 没有Name 成员,所以将data 参数声明为any,而不是Teacher

this.subscription= this.techerService.getDataById(this.id).subscribe((data:any) =>{
       console.log(data);
       this.model.name=data.Name;
       console.log(this.model);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    相关资源
    最近更新 更多