尝试从对象的可观察数组迭代* ngFor时出现错误
我使用Angular 8
聊天消息服务
private chatMessages = [];
private chatMessagesStream = new BehaviorSubject(this.chatMessages);
getMessages(): Observable<any> {
return this.chatMessagesStream.asObservable();
}
addMessage(chatMessage) {
this.chatMessages.push(chatMessage);
this.chatMessagesStream.next(this.chatMessages);
}
聊天视图组件
private chatMessages:Observable<Array<any>>;
constructor(
private chatMessagesService: ChatMessagesService) {
}
ngAfterViewInit() {
this.chatMessagesService.getMessages().subscribe(messages => {
this.chatMessages = messages;
this.scrollMessagesToBottom(true);
});
}
聊天HTML模板
<div class="row conpeek_message_chat_row" *ngFor="let chatMessage of chatMessages | async ">
...
</div>
在初始化组件之后,我在控制台中遇到问题,这可能是什么问题?
ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
答案 0 :(得分:1)
删除异步管道
由于chatMessages
是不可观察的,因此它包含纯值。
this.chatMessagesService.getMessages().subscribe(messages => {
this.chatMessages = messages; // <------- HERE , you are assigning value
this.scrollMessagesToBottom(true);
});
如果要保持异步管道,则必须为chatMessages
分配observable
,如下所示:
this.chatMessages = this.chatMessagesService.getMessages();