chatroom.service.ts:Angular + Firebase:如何使用列表屬性存儲/檢索對象?
...
export class Message {
author: string;
body: string;
}
export class Chatroom {
title: string;
messages: Message[]; // <-- seems to be the problem
}
@Injectable()
export class ChatroomService {
...
getChatroom = (chatroomId: string): FirebaseObjectObservable<Chatroom> =>
this.db.object('/chatrooms/' + chatroomId);
...
chatroom.component.ts:
...
export class ChatroomComponent implements OnInit {
chatroom: Chatroom;
private sub: any;
ngOnInit() {
this.sub = this.route.params
.subscribe(params => {
this.sub = this.chatroomService.getChatroom(params['chatroomId'])
.subscribe(chatroom => this.chatroom = chatroom);
});
}
...
chatroom.component.html
<div *ngIf="chatroom">
<p *ngFor="let message of chatroom.messages">{{message.author}}: {{message.body}}</p>
</div>
錯誤:
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
的問題在於聊天室對象的「消息」屬性被Firebase視爲對象,而我希望它被視爲ngFor-iterable列表。有關如何完成這項工作的任何建議?
編輯:這裏是火力地堡數據結構:
{
"chatrooms" : {
"chatroom_342768235" : {
"title" : "a chatroom",
"messages" : {
"message_3252253" : {
"author" : "Joe",
"body" : "test message"
},
"message_2653837" : {
"author" : "Kim",
"body" : "another message"
}
}
},
"chatroom_426482763" : {
"title" : "another chatroom",
"messages" : {
"message_1243525" : {
"author" : "Tom",
"body" : "blah blah"
}
}
}
}
}
顯示聊天室內部是什麼? – Sajeetharan
你使用的是angularfire2(https://github.com/angular/angularfire2)嗎? – happyZZR1400