How to fix InvalidPipeArgument error when iterate *ngFor from Observable Array of Objects

江枫思渺然 提交于 2019-12-25 00:18:55

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!