在Angular中,如果API返回的是对象数组而不是单个对象,我们需要在使用HTTP GET请求获取数据时设置响应类型为'json”。这是因为默认情况下,Angular会将API返回的JSON数据解析为单个对象而不是对象数组。这可以通过以下方式进行解决:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('https://myapi.com/data', { responseType: 'json' });
}
}
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
template: `
- {{ item.name }}
`
})
export class AppComponent {
data: any;
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getData().subscribe((response: any) => {
this.data = response;
});
}
}
通过上述两种方法,就可以正确地将API返回的对象数组解析为对象数组而不是单个对象。