typescript 如何检查多个条件以将可观察项与rxjs连接

6ss1mwsb  于 2023-01-31  发布在  TypeScript
关注(0)|答案(2)|浏览(128)

我想对可观察的消息设置检查条件,并将输出定制为如下场景:检查消息是否是给我或从我和连接20第一个字符与名称的朋友或如果它是我的消息与检查消息的类型,如果它是一张照片或文件,使一个消息,例如你发送了一个attament

getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
    let message: Observable<string>;
   
    const messageModel = this.allDirectMessages$
      .pipe(
        map((x) =>
          x.filter(
            (f) =>
              f.messageModel.to.userName === onlineUserModel.userName ||
              f.messageModel.from.userName === onlineUserModel.userName
          )
        )
      )
      .pipe(map((data) => data[data.length - 1].messageModel))
      .pipe(
        map((item) => {
          if (item.to.userName == onlineUserModel.userName) {
            message = concat("You", item.content, "...");
          }
          else (item.to.userName == onlineUserModel.userName) {
            message = concat("You", item.content, "...");
          }
        })
      );

   
    return message;
  }
lymnna71

lymnna711#

如果你想以Observable<string>的形式返回消息,你可以这样做:

getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {   
  return this.allDirectMessages$
    .pipe(
      filter((f) =>
          f.messageModel.to.userName === onlineUserModel.userName ||
          f.messageModel.from.userName === onlineUserModel.userName
      ),
      map((data) => {
        const item = data[data.length - 1].messageModel;
        if (item.to.userName == onlineUserModel.userName) {
          return `You ${item.content}...`;
        }
        else (item.from.userName == onlineUserModel.userName) {
          return `Them ${item.content}...`;
        }
      })
    );
}
stszievb

stszievb2#

我尝试与您分享我的结果,只是在filter之前添加了map运算符:

getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {   
  return this.allDirectMessages$
    .pipe(
      filter((f) =>
          f.messageModel.to.userName === onlineUserModel.userName ||
          f.messageModel.from.userName === onlineUserModel.userName
      ),
      map((data) => {
        const item = data[data.length - 1].messageModel;
        if (item.to.userName == onlineUserModel.userName) {
          return `You ${item.content}...`;
        }
        else (item.from.userName == onlineUserModel.userName) {
          return `Them ${item.content}...`;
        }
      })
    );
}

相关问题