Angular .json()强制小写翻译

时间:2017-11-26 21:34:15

标签: json angular

环境:带有Angular的ASP.NET MVC核心

经过几个小时的故障排除后,我遇到的问题是Angular.json()函数需要我的类以特定的表示法。

ASP.NET模型

public class ElementProperty
{
    public int Id { get; set; }
    public int ElementId { get; set; }
    public string Name { get; set; }
}

ASP.NET控制器

// GET: api/ElementProperties
[HttpGet]
public IEnumerable<ElementProperty> GetElementProperties()
{
    return _context.ElementProperties;
}

角度组件

你会认为这个组件可行。

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'ElementProperty',
    templateUrl: './ElementPropertyComponent.html'
})
export class ElementPropertyComponent {
    public Properties: ElementProperty[];

    constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
        http.get(baseUrl + 'api/ElementProperties').subscribe(result => {
            this.Properties = (result.json() as ElementProperty[]);
        }, error => console.error(error));
    }
}

interface ElementProperty {
    Id: number;
    ElementId: number;
    Name: string;
}

它没有:(

只有当我将接口ElementProperty更改为使用小写的第一个字母,并且当然更改所有对它的引用时,它是否有效。

我想我有两个问题:

  1. 我可以使用一个设置来使json()遵守 翻译定义或至少创建一个翻译? (它&#39; S 不清楚这只是第一个字母......我会对此进行调查 进一步)
  2. 为什么会这样做?

1 个答案:

答案 0 :(得分:0)

注意:我已将此评论移至答案,因为在我看来,这是原始问题的答案。

我遇到了同样的问题,并在GitHub上发现了以下讨论:link

重点是在ConfigureServices方法中使用此行:

services.AddMvc()
        .AddJsonOptions(options =>
            options.SerializerSettings.ContractResolver = 
               new DefaultContractResolver());

当然也加载Newtonsoft.Json.Serialization;

相关问题