【发布时间】:2020-01-08 19:48:36
【问题描述】:
我订阅了一个 obserable 以获取在 angular 8 中工作正常的数据。我需要在使用映射时格式化日期我收到错误提示
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
所以我相信添加地图运算符并更改返回类型。我不确定我实施地图的方式有什么问题。有人可以告诉我吗?
export interface IPersonNote {
id: number;
personId: number;
note: string;
authorId: number;
authorName: string;
fileName: string;
mimeType: string;
alias: string;
createdBy: string;
createdDate: Date;
}
原始方法
import { map } from 'rxjs/operators';
public personNotes: IPersonNote;
loadPersonNotes() {
this.isCurrentUser = this.id !== this.userService.getCurrentUser().id;
this.userService.getPersonNote(this.id)
.subscribe((x: IPersonNote) => {
this.personNotes = x;
});
}
修改方法
import { map } from 'rxjs/operators';
public personNotes: IPersonNote;
loadPersonNotes() {
this.isCurrentUser = this.id !== this.userService.getCurrentUser().id;
this.userService.getPersonNote(this.id)
.pipe(map(note => <any>{
createdDate: format(note.createdDate, 'Do MMM YYYY'),
}))
.subscribe((x: IPersonNote) => {
this.personNotes = x;
});
}
用户界面
<div *ngIf="personNotes">
<div class="portlet-body">
<ul class="tier-history">
<li *ngFor="let note of personNotes">
<span class="tier-title"> {{ note.authorName }} </span>
<span class="tier-dates">
{{ note.created }}
</span>
<span class="tier-title"> {{ note.note }} </span>
</li>
</ul>
</div>
</div>
服务
public getPersonNote = (id: number): Observable<IPersonNote> =>
this.http.get<IPersonNote>(`${this.baseUrl}person-note/${id}`)
【问题讨论】:
-
IPersonNote只是一个结构,不可迭代。为什么你的变量使用复数pesonNotes而类型是单数IPersonNote?为什么要对结构执行 ngFor?这只是 1 个注释实例。 -
personNotes是一个对象,而不是数组,因此您会看到错误...您需要在数组上使用 *ngFor,而不是对象。 -
不。我现有的方法返回多条记录,并且显示正确。只有在地图之后我才收到此错误
-
将 personNotes 声明为数组 ex:
public personNotes: IPersonNote[];并订阅 ...subscribe((x: IPersonNote[]) => {。它会工作 -
好的,但是我如何使用地图来转换日期格式。如果你在修改后的代码部分看到我的帖子
标签: angular