从另一个可观察对象的.subscribe函数返回一个可观察对象

时间:2020-06-20 10:33:15

标签: angular typescript google-cloud-firestore observable subscribe

我在Angular中用Typescript观察到一个小问题。 无效下的代码不起作用,更多是为了理解我想做什么。

getRefuels(): Observable<Refuel[]> {
    return new Observable<Refuel[]>((obs) => {
        this.hashService.getHashedUserEmail().subscribe((hashValue) => {

            //This is the observable I want to return
            return this.firestore
                .collection<Refuel>(`users/${hashValue}/refuels`, ref => ref.orderBy('date', 'desc'))
                .valueChanges({idField: 'id'});

        });
    });
}

我尝试添加一个.pipe(map(res => { return res; })),但并没有完全满足我的要求。 我也尝试了以下代码,但是数据类型不合适:

obs.next(this.firestore
  .collection<Refuel>(`users/${hashValue}/refuels`, ref => ref.orderBy('date', 'desc'))
  .valueChanges({idField: 'id'}));

obs.complete();

当我订阅了我的Firestore可观察对象,然后将结果列表放入obs.next()时,它起作用了,但是这样我就不再获得列表更新了。

您知道我该如何解决吗?

1 个答案:

答案 0 :(得分:1)

当您有2个可观测对象时,可以使用switchMap运算符

first_observable.pipe(
  switchMap(result => {
   // do something with the result
   return second_observable;
   })
).subscribe(second_result => {
   // do something with result of second observable
});