簡體   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