【发布时间】:2019-08-18 08:57:16
【问题描述】:
每当我尝试在我的 http.get(url) 调用中使用 {{requestType: 'text'}} 时,我都会收到一个错误,我无法区分并且只允许使用数组和可迭代对象;但是,我将我的对象转换为一个数组。我需要一些帮助来了解我的错误以及如何解决我的情况
当我删除 RequestType 时,数组没有问题并显示在我的前端。
----service-----
getAll(){
const requestOptions: Object = {
/* other options here */
responseType: 'text'
}
return this.http.get<any>(this.url, requestOptions);
}
---component .ts-----
notificationsFass: any[];
constructor(route: ActivatedRoute, private metaService: Meta, private notificationService: NotificationsFassService) {
this.notificationsFass = [];
}
ngOnInit() {
this.notificationService.getAll()
.subscribe(notificationsFass => {
this.notificationsFass = notificationsFass;
}
);
}
---html---
<div *ngFor="let m of notificationsFass">
---error----
ERROR Error: Error trying to diff '[{"incidentNumber":700,"createdByName":"FASS Notification","createdDate":"2019-03-27T09:18:15.000+0000"}]'. Only arrays and iterables are allowed
【问题讨论】:
-
从服务器发送的实际内容类型是什么?如果内容类型是
application/json,则没有理由使用responseType: 'text'。错误中显示的“数据”看起来是 JSON,因此您可以使用默认的responseType以便 HttpClient 解析接收到的 JSON 以在您的模板中使用。您想使用responseType: 'text'的原因是什么? -
但是,我将我的对象转换为一个数组。:在哪里?发布的代码不会在任何地方这样做。您正在尝试遍历字符串。
-
是 application/json ;但是,当我的服务器无法从我读过的内容中呈现 JSON 时,我会从服务器收到 httpResponse 错误,如果我可以拥有 httpResponse 文本,我可能会摆脱这些错误
-
不,您从服务器获取文本响应(字符串)并覆盖空数组
notificationFass。 -
对,
*ngFor只能渲染特定格式的对象,例如对象数组。如果您的内容类型是application/json,绝对不要使用responseType: 'text'。它不会被解析,只是一个字符串,在任何情况下都不能被结构指令使用,例如*ngFor。您可能应该分享在textresponseType更改并将其转换为数组之前获取响应的逻辑。
标签: angular typescript http rxjs