2017-06-04 43 views
0

chatroom.service.ts:角度+ 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. 

問題はそれですChatroomオブジェクトの "message"プロパティはFirebaseによってオブジェクトとして扱われますが、これはngFor-iterableリストとして扱われます。どのようにこの作品を作るための任意の提案?

EDIT:リストのようなもので

{ 
    "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

anglefire2(https://github.com/angular/angularfire2)を使用していますか? – happyZZR1400

答えて

0

私はあなたが観察可能なリストを取得する(サブスクライブして)DBを聞くためだと思う、と* ngForカントの仕事:ここFirebaseデータ構造があります。反復したいObservableリストの後に| asyncのパイプを追加してみてください。このような何か:

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

可能であればChatroomクラスにmessagesプロパティにセッター/ゲッターメソッドを追加します。

messagestyped arrayと宣言してください。このアプローチmessagesプロパティで

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; 
    } 

} 

文字列インデックスとの適切な配列であり、今で反復可能でなければなりません。型付き配列を使用する理由は、メッセージmessage_2653837message_3252253の名前にアクセスできることだけです。

関連する問題