这是因为Angular HttpClient在默认情况下使用的是ResponseType.Json,它将响应体解析为JSON对象,而在JSON对象中,数组类型通常被视为对象。解决方法是在请求时指定responseType为"text",然后手动将响应转换为JSON对象并处理其中的数组。如下所示:
import { HttpClient, HttpResponse } from '@angular/common/http';
//...
this.http.get('assets/data.json', { responseType: 'text' }).subscribe((response: HttpResponse) => {
const data = JSON.parse(response.body);
const array = data.array.map((value: string) => {
return { name: value };
});
console.log(array);
});
在上面的示例中,我们将responseType设置为"text",这样HttpClient将返回响应体的原始字符串形式,然后我们手动将其转换为JSON对象,并使用map方法将其转换为我们需要的对象数组。