【问题标题】:Only render recent changes Firestore + Angular Chat app仅呈现最近的更改 Firestore + Angular Chat 应用
【发布时间】:2021-06-08 09:27:48
【问题描述】:

我创建了一个使用 firestore(使用 angularfire 包装器)和 angular 的聊天应用程序,它正在工作。数据库结构是这样的。我对每个用户都有唯一的 ID。当有人(发件人)向其他人(收件人)发送消息时,我会将消息添加给发件人:

collection("messages") => doc(sender's ID) => collection(receiver's ID) => doc(message ID)

另外,我向接收者添加了相同的消息:

collection("messages") => doc(receiver's ID) => collection(sender's ID) => doc(message ID)

现在,当用户(发送者)打开与另一个用户(接收者)的聊天时,我将侦听器(valueChanges)附加到:

collection("messages") => doc(sender ID) => collection(receiver ID)

集合中的每条消息的结构如下:

message: 'string message'
profilePic: 'url for profile pic'
senderId: 'unique id of sender'
timestamp: some timestamp

使用此配置一切正常,但存在一些问题。

  1. 每当添加新消息时,“valueChanges”都会监听更改并将值分配给数组“chats”。 'chats' 数组与 *ngFor 一起使用来显示消息的内容。每当我收到更改时就会出现问题,整个消息列表都会重新呈现,包括个人资料图片。理想情况下,应该只呈现最近的更改。
  2. 没有办法(或者我想不到)查询每个用户的最新消息。

【问题讨论】:

    标签: angular firebase angularfire2 angularfire


    【解决方案1】:

    使用valueChanges 会很简单,但您会看到问题以及数据库使用成本。所以我建议你看看snapshotChanges

    您可以按照以下方式分离逻辑。

    • 使用valuechangesfirst/或take(1) 运算符在进入时加载所有消息。
    this.messages = await this.afs.collection('messages')
      .valuechanges()
      .pipe(take(1))
      .toPromise();
    
    • 而且你必须在 Angular 端监听最近的变化并修改数组。
    // manage recently added messages
    this.afs.collection('messages').snapshotChanges(['added'])
      .pipe(takeUntil(untilFn))
      .subscribe(added => {
        this.messages = [...added, this.messages];
    });
    
    // manage recently removed messages
    this.afs.collection('messages').snapshotChanges(['removed'])
      .pipe(takeUntil(untilFn))
      .subscribe(removed => {});
    
    // manage recently modified messages
    this.afs.collection('messages').snapshotChanges(['modified'])
      .pipe(takeUntil(untilFn))
      .subscribe(modified => {});
    

    请注意snapshotChanges 的返回类型与valueChanges 不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多