获取uid并使用Angular4和Fireabse迭代一个对象数组

时间:2021-10-27 14:26:18

I am building a 1-1 chat using Angular4 and Firebase and I am pretty new to Angular. In order to initiate a conversation, I am trying to display all available users form '/users' subcollection. So, I need to get user/{user.uid}/username.

我正在用Angular4和Firebase建立1-1聊天,我对角度很陌生。为了启动对话,我尝试显示所有可用的用户表单'/users' subcollection。因此,我需要获取user/{user.uid}/username。

This is my chat.component.ts:

这是我chat.component.ts:

import { Component, OnInit } from '@angular/core';
import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import { UserSessionService } from '../_services/user-session.service';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
  items: FirebaseListObservable<any[]>;
  other_users: FirebaseListObservable<any[]>;
  user_id: any;
  from: any;
  msgVal: string = '';


  constructor(public afAuth: AngularFireAuth, public af: AngularFireDatabase, public logged_user: UserSessionService ){ }

    ngOnInit() {

      this.from= this.logged_user.getFirebaseUid();
      this.user_id= this.logged_user.getFirebaseUid();

      this.items = this.af.list('/personalMessages', {
      query: { limitToLast: 5  }
    });

    this.other_users= this.af.list('/users');

  }

  findChat(){
    this.other_users= this.other_users;
     this.user_id = this.user_id;    
  }

    chatSend(theirMessage: string) {     
      this.items.push({ text: theirMessage, from: this.logged_user.getFirebaseUid(), isRead: false, timestamp: + new Date()  });
      this.msgVal = '';
      this.user_id = this.user_id;
      this.other_users= this.other_users;
  }

}

And this is my chat.component.html:

这是我的聊天。component。html:

<div class="users-chat-container" *ngFor="let other_user of other_users| async">
      <div id="circle" style="background-color:pink;">        
      </div>
     <br/> <a href="#">{{other_user.username}}  </a>    

    </div>


    <div class="chat-container" *ngFor="let item of items | async">
      <div id="circle" style="background-image:url( http://www.ics.forth.gr/mobile/female.png);">        
      </div>
     <br/> <a href="#">{{item.from}}  </a>    
      <p>{{item.text}}</p>
    </div>
     <input type="text" id="message" placeholder="Type a message..." (keyup.enter)="chatSend($event.target.value)" [(ngModel)]="msgVal" />

How can I iterate over the array of objects I get from '/users' collection? Thank you! :)

如何迭代从'/users'集合中获得的对象数组?谢谢你!:)

2 个解决方案

#1


2  

you need use ForkJoin. ForkJoin will take users list as input and fire parallel request for all users list

你需要使用ForkJoin。ForkJoin将以用户列表为输入,并对所有用户列表进行并行请求。

try some thing like this

试试这样的东西

this.af.list('/users')
            .mergeMap((users) => {
               if (users.length > 0) {

                return Observable.forkJoin(
                    users.map((user) => this.af.database
                        .object(`user/${user.$uid}/username`)
                        .first()
                    ),

                    (...values) => { // here you can assign username 
                        users.forEach((user, index) => { user.username = values[index]; });
                        return users;
                    }
                  );
          }
          return Observable.of([]);
            });

more info about forkJoin https://www.learnrxjs.io/operators/combination/forkjoin.html

更多关于forkJoin的信息:https://www.learnrxjs.io/operators/combination/forkjoin.html

#2


1  

You need an array for *ngFor. With object.keys you can create an array of the objects. In the example below I have done this with players from a group, coming as objects from firebase.

您需要一个*ngFor数组。与对象。可以创建对象数组的键。在下面的示例中,我使用了来自一个组的玩家,作为来自firebase的对象。

private getPlayersPerGroup(group: Group) {
    this.playersInGroup = [];
    if (group["players"]) {
        Object.keys(group["players"]).forEach((key) => {
            this.groupService.getPlayerById(key).then((player) => {
                this.playersInGroup.push(player);
            });
        });
    }
}

#1


2  

you need use ForkJoin. ForkJoin will take users list as input and fire parallel request for all users list

你需要使用ForkJoin。ForkJoin将以用户列表为输入,并对所有用户列表进行并行请求。

try some thing like this

试试这样的东西

this.af.list('/users')
            .mergeMap((users) => {
               if (users.length > 0) {

                return Observable.forkJoin(
                    users.map((user) => this.af.database
                        .object(`user/${user.$uid}/username`)
                        .first()
                    ),

                    (...values) => { // here you can assign username 
                        users.forEach((user, index) => { user.username = values[index]; });
                        return users;
                    }
                  );
          }
          return Observable.of([]);
            });

more info about forkJoin https://www.learnrxjs.io/operators/combination/forkjoin.html

更多关于forkJoin的信息:https://www.learnrxjs.io/operators/combination/forkjoin.html

#2


1  

You need an array for *ngFor. With object.keys you can create an array of the objects. In the example below I have done this with players from a group, coming as objects from firebase.

您需要一个*ngFor数组。与对象。可以创建对象数组的键。在下面的示例中,我使用了来自一个组的玩家,作为来自firebase的对象。

private getPlayersPerGroup(group: Group) {
    this.playersInGroup = [];
    if (group["players"]) {
        Object.keys(group["players"]).forEach((key) => {
            this.groupService.getPlayerById(key).then((player) => {
                this.playersInGroup.push(player);
            });
        });
    }
}