Parse JSON strnig from API in angular

随声附和 提交于 2020-01-13 19:00:32

问题


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"
  }
]   

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);

    });
  }

} 

My model file looks like this:

export class Symbols {

  constructor(private symbol: string, private series: string, private isin: string, private created: string) {

  }

}

After getting response from the API i need to populate the result in allSymbols variable.


回答1:


You JSON object properties are not 100% mapping for Symbols, you have to convert it.

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 would return a list of ServerSymbols

export interface ServerSymbols {
    id: number;
    symbol: string;
    series: string;
    isin: string;
    created_at: string;
    updated_at: string;
}

Convert ServerSymbols object to Symbols object:

convertFromServer(serverSymbols: ServerSymbols): Symbols {
    return new Symbols(serverSymbols.symbol, serverSymbols.series, serverSymbols.isin, serverSymbols.created_at);
}


来源:https://stackoverflow.com/questions/49156433/parse-json-strnig-from-api-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!