gpt4 book ai didi

node.js - 使用 Angular 4 和 Firebase 获取 uid 并迭代对象数组

转载 作者:搜寻专家 更新时间:2023-11-01 00:37:55 24 4
gpt4 key购买 nike

我正在使用 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”集合中获取的对象数组?谢谢! :)

最佳答案

你需要使用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

关于node.js - 使用 Angular 4 和 Firebase 获取 uid 并迭代对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45038085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com