繁体   English   中英

Rxjs:使用 function 中的 observable 值返回 promise/observable

[英]Rxjs: use values of observables in function that return promise/observable

所以我有返回 Promise 的链接函数,在 arguments 中我需要使用 observables 的值。 看代码中的描述就明白了。 我想我应该使用一些 rxjs 运算符以反应式编程方式编写此代码? 但我现在不知道如何准确地做到这一点,使用它们中的哪一个。

interface User {
  email: string;
  conversations: string[] | FieldValue;
  userId: string;
}

@Injectable({
  providedIn: 'root',
})
export class ConversationsClientService {
  getUserByEmail(email: string): Observable<any> {
    // should return Observable<User[]> but this function return type is Observable<unknown[]> and i can't use this type, but thats not the main issue
    return this.firestore
      .collection('users', (ref) => ref.where('email', '==', email))
      .valueChanges();
  }

  startNewConversation(
    currentUserCredential: Observable<firebase.auth.UserCredential>, //that comes from ngrx selector
    email: string
  ): Promise<void> {
    //or return observable by wrapping promise with from() operator
    return this.firestore
      .doc<User>(
        'users/' + 'there should be .user.uid field of value of observable currentUserCredential'
      )
      .update({
        conversations: arrayUnion(
          'there should be [0].userId field of value of observable getUserByEmail(email)'
        ),
      });
  }

  constructor(private firestore: AngularFirestore) {}
}

I would advise to go with the from operator instead of a Promise and model the whole operation as a RxJs stream.

一种选择是:

  startNewConversation(
    currentUserCredential: Observable<firebase.auth.UserCredential>, //that comes from ngrx selector
    email: string
  ): Promise<void> {
    /* combineLatest will emit an array with the most recent emitted values of the combined observables */
    return combineLatest([currentUserCredential, this.getUserByEmail(email)]).pipe(
      switchMap((currentUserAndUserByEmail) => {
        return from(this.firestore
          .doc<User>(
            'users/' + currentUserAndUserByEmail[0].user.uid,
          )
          .update({
            conversations: arrayUnion(
              currentUserAndUserByEmail[1][0].userId
            ),
          }))
      } )
    )
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM