自定义对象的有角竞标数组-来自httpget的属性的大写/小写发行名称

问题描述 投票:1回答:2

我正在做什么的描述。

我正在尝试显示来自服务器的自定义对象的表。我正在调用httpclient.get并将json转换为我的自定义对象的数组(使用httpclient中的内置功能),并在subscribe函数中提交给自己的属性。接下来,我尝试使用绑定和* ngFor将内容显示到表中。代码后部分显示了问题。我正在使用Angular-8。

代码

所有代码都经过简化以显示问题。为了简单起见,我还将服务移至组件。

最简单的班级:

export class Person {
    public Name: string;
}

我的组件

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Person } from '../models/person';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  public persones: Array<Person>;

  constructor(
    private http: HttpClient
  ) { }

  ngOnInit() {
    this.getPeople();
  }

  private getPeople(): void {
    this.http.get<Array<Person>>('https://localhost:44368/api/person')
    .subscribe(      
      x => this.persones = x,
      () => console.log('error getting people')    
    );

  }
}

HTML部分

<div>
  <table class="table">
    <thead class="thead-dark">
      <tr>
        <th>name lowercase</th>
        <th>Name Upercase</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor='let item of this.persones'>
        <td>{{ item.name }}</td>
        <td>{{ item.Name }}</td>
      </tr>
    </tbody>
  </table>
</div>

问题

问题是在html中显示具有item.name(小写)的表,而显示item.Name(大写)的表[,并且我自己的属性的属性为大写字母。我很例外,根据我的经验,当投射到有角度的对象时,我应该使用这些自定义对象的属性。我知道这些小写字母来自服务器的json,但应从angular转换为对象。

我试图像使用

as或使用Observable进行转换,但没有帮助。

同样,当我改变

persnones

的类型并改变类型时,我得到相同的结果public persones: string; this.http.get<string> ...blabla...
我仍然得到相同的结果,因此我的persones属性被视为典型的json对象。
angular typescript http-get angular-components subscribe
2个回答
2
投票
Typescript是一个构建时构造-在运行时是JavaScript,类型无关紧要。它不会为您做任何魔术映射,因此,如果服务器返回名称为小写字母的数组,则将得到此结果。

诊断此问题的最佳方法是检查开发人员工具中的网络请求,并相应地调整您的类型,或将传入的对象映射为所需的格式


0
投票
我建议使用小写的属性名称,因为它是json响应的默认行为。

但是,请回答您的问题。这可以通过配置OutputFormatter(.net后端)

解决。

public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc() .AddMvcOptions(options => { options.OutputFormatters.Add(new PascalCaseJsonProfileFormatter()); }); }

© www.soinside.com 2019 - 2024. All rights reserved.