问题
I have an error when try to iterate *ngFor from Observable Array of Objects
I use Angular 8
Chat messages Service
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);
}
Chat View Component
private chatMessages:Observable<Array<any>>;
constructor(
private chatMessagesService: ChatMessagesService) {
}
ngAfterViewInit() {
this.chatMessagesService.getMessages().subscribe(messages => {
this.chatMessages = messages;
this.scrollMessagesToBottom(true);
});
}
Chat HTML template
<div class="row conpeek_message_chat_row" *ngFor="let chatMessage of chatMessages | async ">
...
</div>
After init component i have an issue in console, what could be wrong ?
ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
回答1:
Remove async pipe
As chatMessages
is not observable, its contains pure value.
this.chatMessagesService.getMessages().subscribe(messages => {
this.chatMessages = messages; // <------- HERE , you are assigning value
this.scrollMessagesToBottom(true);
});
If you want to keep async pipe, you have to assign chatMessages
with observable
, like this :
this.chatMessages = this.chatMessagesService.getMessages();
来源:https://stackoverflow.com/questions/57613718/how-to-fix-invalidpipeargument-error-when-iterate-ngfor-from-observable-array-o