从Angular中的API解析JSON strnig [英] Parse JSON strnig from API in angular

查看:74
本文介绍了从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);
}

这篇关于从Angular中的API解析JSON strnig的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆