从Angular中的API解析JSON strnig
我有一个API返回以下数据:
I have a API returning following data:
[
{
"id": 1,
"symbol": "20MICRONS",
"series": "EQ",
"isin": "INE144J01027",
"created_at": "2018-03-05 16:24:10",
"updated_at": "2018-03-05 16:24:10"
},
{
"id": 2,
"symbol": "3IINFOTECH",
"series": "EQ",
"isin": "INE748C01020",
"created_at": "2018-03-05 16:24:10",
"updated_at": "2018-03-05 16:24:10"
},
{
"id": 3,
"symbol": "63MOONS",
"series": "EQ",
"isin": "INE111B01023",
"created_at": "2018-03-05 16:24:10",
"updated_at": "2018-03-05 16:24:10"
},
{
"id": 4,
"symbol": "VARDMNPOLY",
"series": "EQ",
"isin": "INE835A01011",
"created_at": "2018-03-05 16:24:10",
"updated_at": "2018-03-05 16:24:10"
}
]
我希望以角度解析来自api的响应.我可以在控制台中记录数据,但不能在数据类型中进行映射.
I wish to parse this response from api in angular. I am able to log the data in console but not able to map in the datatype.
export class SymbolsComponent implements OnInit {
allSymbols: Symbols[] = [];
constructor(private http: HttpClient, private apiUrl: ApiUrlService) { }
ngOnInit() {
this.fetchListOfAllSymbol();
}
fetchListOfAllSymbol() {
this.http.get(this.apiUrl.getBaseUrl() + 'symbol').subscribe(data => {
console.log(data);
});
}
}
我的模型文件如下:
export class Symbols {
constructor(private symbol: string, private series: string, private isin: string, private created: string) {
}
}
从API获得响应后,我需要在allSymbols
变量中填充结果.
After getting response from the API i need to populate the result in allSymbols
variable.
您的JSON对象属性不是Symbols
的100%映射,您必须对其进行转换.
You JSON object properties are not 100% mapping for Symbols
, you have to convert it.
这里是一个示例,接口ServerSymbols
包含JSON对象的所有属性,现在您可以将fetchListOfAllSymbol()
修改为:
Here's an example, interface ServerSymbols
contains all properties of the JSON object, now you can modify fetchListOfAllSymbol()
as:
fetchListOfAllSymbol() {
this.http.get<ServerSymbols[]>(this.apiUrl.getBaseUrl() + 'symbol')
.subscribe((data: ServerSymbols[]) => {
console.log(data);
// convert ServerSymbols to Symbols
});
}
GET将返回ServerSymbols列表
GET would return a list of ServerSymbols
export interface ServerSymbols {
id: number;
symbol: string;
series: string;
isin: string;
created_at: string;
updated_at: string;
}
将ServerSymbols对象转换为Symbols对象:
Convert ServerSymbols object to Symbols object:
convertFromServer(serverSymbols: ServerSymbols): Symbols {
return new Symbols(serverSymbols.symbol, serverSymbols.series, serverSymbols.isin, serverSymbols.created_at);
}