【发布时间】:2019-09-19 14:28:22
【问题描述】:
SampleDataController:
[HttpGet("GetAllItems")]
public async Task<IActionResult> GetAllItems()
{
return Json(await _storeContext.Table.AsQueryable().ToListAsync());
}
数据服务:
export class DataService {
constructor(private http: HttpClient) { }
GetAllItems() {
return this.http.get("https://localhost:44381/api/SampleData/GetAllItems");
}
}
组件:
import { Component } from '@angular/core';
import { DataService } from '../store.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public itemsList: Item[];
constructor(private logger: DataService) {}
GetItems() {
this.logger.GetAllItems().subscribe(
data => this.itemsList = <Item[]>JSON.parse(JSON.stringify(data))
)
}
}
export interface Item {
Id: number;
Name: string;
Surname: string;
}
组件html:
<button mat-button (click)="GetItems()">GetItems!</button>
<li *ngFor="let item of itemsList">
<span>
<br />
{{item.Name}}
<br />
{{item.Surname}}
</span>
</li>
点击按钮GetItems() 后返回对象数组。我认为data => this.itemsList = <Items[]>JSON.parse(JSON.stringify(data)) 应该转换为Item 的数组,我应该得到Item[] 数组。在 TypeScript 中将 json 转换为类型化数组的正确方法是什么?
Json 数据示例:
[
{
"id": 3,
"name": "1",
"surname": "2 "
},
{
"id": 4,
"name": "1",
"surname": "2 "
},
{
"id": 5,
"name": "1",
"surname": "2 "
},
【问题讨论】:
标签: c# json angular asp.net-core