我尝试使用名为feed.component.html
的以下模板在Feed上显示消息
<div class="feed">
<div *ngFor="let message of feed | async" class="message">
<app-messages [chatMessage]="message"></app-messages>
</div>
</div>
我一直收到以下错误,无法在html聊天页面上显示我发送到Firebase数据库的消息。
错误错误:InvalidPipeArgument:&#39; [object Object]&#39;用于管道 &#39; AsyncPipe&#39;
我还获得了feed.component.ts
文件,如下所示:
import { Component, OnInit, OnChanges } from '@angular/core';
import { ChatService } from '../services/chat.service';
import { Observable } from 'rxjs/observable';
import { ChatMessage } from '../models/chat-message.model';
import { AngularFireList } from 'angularfire2/database';
@Component({
selector: 'app-feed',
templateUrl: './feed.component.html',
styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit, OnChanges {
feed: AngularFireList<ChatMessage[]>;
constructor(private chat: ChatService) { }
ngOnInit() {
console.log("feed init...")
this.feed = this.chat.getMessages();
}
ngOnChanges() {
this.feed = this.chat.getMessages();
}
}
我还在下面找到了messages.components.ts
文件:
import { Component, OnInit, Input } from '@angular/core';
import { ChatService } from '../services/chat.service';
import { Observable } from 'rxjs/observable';
import { ChatMessage } from '../models/chat-message.model';
@Component({
selector: 'app-messages',
templateUrl: './messages.component.html',
styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
@Input() chatMessage: ChatMessage;
userName: string;
userEmail: string;
messageContent: string;
timeStamp: Date = new Date();
constructor() { }
ngOnInit(chatMessage = this.chatMessage) {
this.messageContent = chatMessage.message;
this.timeStamp = chatMessage.timeSent;
this.userEmail = chatMessage.email;
this.userName = chatMessage.userName;
}
}
任何人都可以告诉我这里有什么问题以及我可以做些什么来解决它?
答案 0 :(得分:1)
我所做的是解决我遇到的问题是更改feed.component.ts文件中的以下代码:
ngOnInit() {
console.log("feed init...")
this.feed = this.chat.getMessages().valueChanges(); // Added `valueChanges`
}
我相信它会从Firebase数据库中获取对象,然后 * ngFor 遍历该对象,为我提供content
,userNames
和{{1}对于每条消息。
如果这个答案有问题,请告诉我,因为我还是很陌生。
干杯。
--- --- UPDATE
我找到的另一种方法是使用服务,我使用Subject作为observable存储我的响应。这使得所有组件都可以访问,这比担心亲子关系更容易。
timestamps
const response = Subject();
const response$ = response.asObservable();
async getData() {
await someApiCall.subscribe((element) => {
this.response.next(element);
})
}
const data = [];
getDataFromService {
this.data = async() => this.service.getDatata();
}
答案 1 :(得分:0)
AngularFireList
用于存储参考路径,以便您可以执行push()
,update()
和remove()
。您需要subscribe
到列表中才能获取值。例如
feedRef: AngularFireList<any>;
feeds: Observable<ChatMessage[]>;
ngOnInit() {
this.feedRef = this.db.list('chats');
this.feeds = this.feedRef.valueChanges();
}
因为您正在从您需要做的聊天服务中获得参考
feeds: Observable<ChatMessage[]>;
ngOnInit() {
this.feeds = this.chat.getMessages().valueChanges();
}