我正在做什么的描述。
我正在尝试显示来自服务器的自定义对象的表。我正在调用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(大写)的表[
as或使用Observable进行转换,但没有帮助。
同样,当我改变persnones
的类型并改变类型时,我得到相同的结果public persones: string;
this.http.get<string> ...blabla...
我仍然得到相同的结果,因此我的persones属性被视为典型的json对象。
诊断此问题的最佳方法是检查开发人员工具中的网络请求,并相应地调整您的类型,或将传入的对象映射为所需的格式
但是,请回答您的问题。这可以通过配置OutputFormatter(.net后端)
解决。public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc()
.AddMvcOptions(options =>
{
options.OutputFormatters.Add(new PascalCaseJsonProfileFormatter());
});
}