Converting JSON response observable to angular (typescript) object array

安稳与你 提交于 2020-12-12 05:51:25

问题


I have a service API that pulls data from Django-REST. The returned JSON looks like:

[
{
    "manufacturer": "Mfg",
    "model": "Model",
},
{
    "manufacturer": "Mfg2",
    "model": "Model2",
}
]

The service API function getData returns:

return this.httpClient.get(`${this.apiURL}/data/`);

Note I am using ListAPIView in Django, and I have verified that the above URL returns the JSON object shown above (though I have to add ?format=json to get the raw data outside of Django's APIView).

I then have an angular component that calls the service API function to convert the observable to an array of objects:

export class Data implements OnInit {

private records = Array<object> = [];

...

constructor(private  apiService:  ApiService) {}

ngOnInit() {
  this.getData();
}

public getData() {
 this.apiService.getData().subscribe((data: Array<object>) => {this.records = data});

There are no error or warnings, but in the component's HTML file when I try to access the record array it always has a length of 0. For example, the following will print "0" and an empty table.

<P> {{ records.length }}</P>
<table>
  <tr>
    <th>Manufacturer</th>
  </tr>
  <tr *ngFor="let record of records">
    <td> {{ record.manufacturer }} </td>
  </tr>
</table>

What am I missing?


回答1:


If you define a model using an interface, and then use that interface as a generic parameter to the get call, the HttpClient will automatically map the response to the defined structure.

For example:

Interface

export interface Product {
  manufacturer: string;
  model: string;
}

Data Service

return this.httpClient.get<Product[]>(`${this.apiURL}/data/`);

Component

private records: Product[];

public getData() {
 this.apiService.getData().subscribe((data: Product[]) => this.records = data);

Template

<div *ngIf="records">
 <p> {{ records.length }}</p>
 ...
</div>

When the template first appears, the async data retrieval process may not yet have finished. So by putting an ngIf around the page, it won't attempt to display the elements until the data is retrieved.




回答2:


you need to add the async pipe to it.

<tr *ngFor="let record of records|async">
    <td> {{ record.manufacturer }} </td>
  </tr>


来源:https://stackoverflow.com/questions/54625967/converting-json-response-observable-to-angular-typescript-object-array

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