【发布时间】:2017-01-16 13:57:56
【问题描述】:
我正在尝试在列表中显示Contacts 的列表:
<h1>Contacts</h1>
<ul>
<li *ngFor="let contact of contacts$ | async">
<ul>
<h1>Name: {{contact.name}}</h1>
<li>ObjectID: {{contact._id}}</li>
<li>LastName: {{contact.lastName}}</li>
<li>FirstName: {{contact.firstName}}</li>
<li>Email: {{contact.email}}</li>
<li>Notes:
<ul *ngFor="let note of contact.notes">
<li>{{note}}</li>
</ul>
</li>
</ul>
</li>
</ul>
contacts$ 是一个Observable<Array<Object>>:
@Component({
selector: 'contacts-list',
templateUrl: 'list.component.html'
})
export class ContactsListComponent implements OnInit {
contacts$: Observable<Array<Object>>;
constructor(private logger: LoggerService,
private router: Router,
private trackerService: TrackerService) {
this.logger.debug(`ContactListComponent.ctor`);
}
ngOnInit() {
this.contacts$ = this.trackerService.cache('tracker/contacts');
}
}
目前,TrackerService.cache(...) 只是从硬编码数组中创建一个 Observable,用于测试:
public cache(path: string): Observable<Array<Object>> {
let retval = [new Object({
_id: '123abc',
lastName: 'last',
firstName: 'first',
email: 'someone@example.com',
notes: ['note 1', 'note 2']
}), new Object({
_id: '123abc',
lastName: 'last',
firstName: 'first',
email: 'someone@example.com',
notes: ['note 1', 'note 2']
})];
return Observable.from(retval)
.map((v) => {
this.logger.debug(`Mapping value: ${JSON.stringify(v)}`);
return v;
});
}
.map() 操作只是为了测试,我在 chrome 控制台中看到了这个:
debug DEBUG: Mapping value: {"_id":"123abc","lastName":"last","firstName":"first","email":"someone@example.com","notes":["note 1","note 2"]}
但是当我运行它时,我得到:
错误:./ContactsListComponent 类 ContactsListComponent 中的错误 - 内联模板:2:8 导致:找不到不同的支持对象 “对象”类型的“[对象对象]”。 NgFor 只支持绑定到 数组等可迭代对象。
我已经阅读了其他 SO 线程、angular.io 和我的 ng2-book,其中有类似的示例,但我只是不明白这一点。
我做错了什么?
【问题讨论】:
-
那么你在控制台中获得了欲望数据吗?
-
this.contacts$.subscribe(value => this.contact = value); this.contacts$ = this.trackerService.cache('tracker/contacts');并在 *ngFor 替换联系人$ |与联系人异步。声明联系人:任何。你需要订阅 observable
-
@AmitSuhag:我认为异步管道为我处理了订阅?这不是异步管道的重点吗?
-
@micronyks:我看到了来自
map调用的调试日志的输出,但我确实没有渲染模板。 -
我不认为你在结果中得到了数组。它只是你得到的一个 json 对象。对吗?
标签: angular observable ngfor