C# 将json字符串强制转换为类型化数组
SampleDataController: 组成部分:C# 将json字符串强制转换为类型化数组,c#,json,angular,asp.net-core,C#,Json,Angular,Asp.net Core,SampleDataController: 组成部分: import { Component } from '@angular/core'; import { DataService } from '../store.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class
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;
}
使用Ok方法(而不是Json)返回序列化对象,使其功能更加完整:
[HttpGet("GetAllItems")]
public async Task<IActionResult> GetAllItems()
{
return this.Ok(await _storeContext.Table.AsQueryable().ToListAsync());
}
在角度方面,默认情况下,假设响应主体包含JSON,因此您可以将服务改写为以下内容:
因此,您不需要手动反序列化任何内容,例如:使用JSON.parse,因为angular将负责此步骤。键入HTTP请求
export class DataService {
constructor(private http: HttpClient) { }
GetAllItems(): Observable<Item[]> {
return this.http.get<Item[]>("https://localhost:44381/api/SampleData/GetAllItems");
}
}
无论如何,还有一些进一步的建议。请使用通用命名规则,方法和成员使用lowerCamelCase。还要避免使用异步管道进行订阅,或者至少取消订阅
<button mat-button (click)="GetItems()">GetItems!</button>
<li *ngFor="let item of itemsList">
<span>
<br />
{{item.Name}}
<br />
{{item.Surname}}
</span>
</li>
[
{
"id": 3,
"name": "1",
"surname": "2 "
},
{
"id": 4,
"name": "1",
"surname": "2 "
},
{
"id": 5,
"name": "1",
"surname": "2 "
},
[HttpGet("GetAllItems")]
public async Task<IActionResult> GetAllItems()
{
return this.Ok(await _storeContext.Table.AsQueryable().ToListAsync());
}
export class DataService {
constructor(private http: HttpClient) { }
GetAllItems(): Observable<Item[]> {
return this.http.get<Item[]>("https://localhost:44381/api/SampleData/GetAllItems");
}
}
export class DataService {
constructor(private http: HttpClient) { }
GetAllItems(): Observable<Item[]> {
return this.http.get<Item[]>("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: Item[]) => this.itemsList = data
)
}
}
export interface Item {
Id: number;
Name: string;
Surname: string;
}