【问题标题】:Get uid and iterate over an array of objects using Angular4 and Fireabse使用 Angular 4 和 Firebase 获取 uid 并遍历对象数组
【发布时间】:2017-12-15 17:24:01
【问题描述】:

我正在使用 Angular4 和 Firebase 进行一对一聊天,而且我对 Angular 还是很陌生。 为了发起对话,我试图从“/users”子集合中显示所有可用用户。所以,我需要获取 user/{user.uid}/username。

这是我的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;
  }

}

这是我的chat.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" />

如何遍历从“/users”集合中获得的对象数组?谢谢! :)

【问题讨论】:

    标签: node.js angular firebase chat angularfire


    【解决方案1】:

    您需要一个用于 *ngFor 的数组。使用 object.keys,您可以创建对象数组。在下面的示例中,我使用来自 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);
                });
            });
        }
    }
    

    【讨论】:

    • 谢谢!我将这样的方法应用于其他对象和对象的对象。 this.whatever= this.personal_conversations.forEach(pc =&gt; { let q = this.changenameafter; this.changenameafter = pc.map(x =&gt; {return x; }); this.changenameafter2 = this.changenameafter.map((entry) =&gt;{ return entry[Object.keys(entry)[0]]; }); });
    【解决方案2】:

    你需要使用ForkJoin。 ForkJoin 将用户列表作为输入,并为所有用户列表触发并行请求

    尝试这样的事情

    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([]);
                });
    

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

    【讨论】:

    • 谢谢!是的,它奏效了。我可以在控制台中看到结果。但是在这里,此时,我可以在我的 chat.component.hmtl 中显示结果吗?使用 *ngFor="let other_user of other_users| async" 我在控制台中收到错误消息,提示错误:InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'。您是否也遇到过这个问题,或者您能帮忙解决吗?谢谢!
    • 发布您的控制台日志结果。也请检查此链接stackoverflow.com/questions/38121908/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2018-08-26
    • 2018-07-02
    • 2021-07-21
    • 2011-06-24
    • 2020-09-23
    相关资源
    最近更新 更多