2017-06-04 123 views
0

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" 
     } 
     } 
    } 
    } 
} 
+1

顯示聊天室內部是什麼? – Sajeetharan

+0

你使用的是angularfire2(https://github.com/angular/angularfire2)嗎? – happyZZR1400

回答

0

我想是因爲你聽DB(與訂閱)你可觀察名單,並* ngFor用那種名單的斜面工作。您應該嘗試在您要迭代的Observable列表之後添加| async管道。事情是這樣的:

<p *ngFor="let message of chatroom.messages | async">{{message.author}}: {{message.body}}</p> 
0

如果可能添加setter/getter方法messages財產Chatroom類。

聲明messages財產爲typed array

export class Chatroom { 
    title: string; 
    private _messages : {[key: string]: Message[]}; 

    public set messages(value: {[key: string]: Message[]}) { 
     this._messages = {}; 
     for (let msg in value) { 
       this._messages[msg] = value[msg]; 
     } 
    } 

    public get messages(): {[key: string]: Message[]} { 
    return this._messages; 
    } 

} 

用這種方法messages性質爲字符串索引正確的陣列,應該是迭代現在。只有使用輸入數組的原因是您可以訪問消息message_2653837message_3252253的名稱。

相關問題