Angular 2 RC和ASP.NET Core JsonResult更改返回对象的大写(使用Observables)

本文关键字:对象 Observables 使用 返回 RC ASP NET JsonResult Core Angular | 更新日期: 2023-09-27 17:57:41

我的C#模型和Angular 2 RC对象都有大写对象。但是,当返回JsonResult时,对象的特性名称的第一个大写字母将变为小写。在我的代码中,似乎没有任何地方的大写字母应该改为小写字母。令人困惑。

性别。cs

public class Gender
{
    [Key]
    public short GenderId { get; set; }
    public string GenderName { get; set; }
}

发电机.ts(视图)

export interface Gender {
    GenderId: number;
    GenderName: string;
}

结果是,我的HTML必须使用小写的第一个字母:{{item.genderName}},即使Intellisense使用{{item.GenderName}},并且使用Intellisense以及代码显示正确的内容,也会阻止显示结果。。

app.component.html

<div style="position:relative">
<h1>Code First Database Migrations</h1>
<ul *ngFor="let item of items">
    <li>{{item.genderName}}</li>
</ul>

这是我的Controller

[HttpGet]
    public JsonResult Get()
    {
        var genders = _context.Genders;
        var query = from g in genders
                    select new { g.GenderId, g.GenderName };
        List<Gender> GenderList = new List<Gender>();
        foreach (var item in query)
        {
            Gender gender = new Gender();
            gender.GenderId = item.GenderId;
            gender.GenderName = item.GenderName;
            GenderList.Add(gender);
        }
        return Json(GenderList);
    }

这是我的DataService:

data.service.ts

import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Gender } from './gender';
import 'rxjs/add/operator/share';
@Injectable()
export class DataService {
public collection$: Observable<Gender[]>;
private _collectionObserver: any;
constructor( @Inject(Http) private http: Http) {
    this.http = http;
    this.collection$ = new Observable(observer => {
        this._collectionObserver = observer;
    }).share();
}
getItems() {
    this.http.get('api/character').map((res: Response) => res.json()).subscribe(items => {
        this._collectionObserver.next(items);
        alert(JSON.stringify(items));
    });
}

}

应用程序组件.ts

import { Inject, Component, Input, OnInit } from '@angular/core';
import { DataService } from './data.service';
import { Gender } from './gender';
@Component({
    selector: 'app',
    templateUrl: 'app/app.component.html'
})
export class AppComponent implements OnInit {
    private items: Gender[];
    constructor( @Inject(DataService) public dataService: DataService) {
    }
    ngOnInit() {
        this.dataService.collection$.subscribe(latestCollection => {
            this.items = latestCollection;
        });
        this.dataService.getItems();
    }
}

Angular 2 RC和ASP.NET Core JsonResult更改返回对象的大写(使用Observables)

这包含在公告中https://github.com/aspnet/Announcements/issues/194

更改惯例修改Startup.cs ConfigureServices方法:

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