是否有一个flatMap等价物返回内部可观察量?

时间:2017-10-11 02:06:20

标签: angular firebase firebase-realtime-database rxjs angularfire

我正在使用AngularFire2而且我正在做这样的事情:

// assume loggedInUserId is Observable<string>
var firebaseList = loggedInUserId
   .flatMap((userId) => this.db.list(this.firebaseRoot.child(userId)))

this.db.list返回FirebaseListObservable<any[]>,其中包含pushdelete等便捷功能,但flatMap仅返回Observable<any[]>,所以我不知道可以访问它们。

是否有等同于flatMap的{​​{1}}?或者这是不可能的?

3 个答案:

答案 0 :(得分:0)

你可以尝试使用map,它会保留firebase中的原始observable

  

编辑:也许施法是答案

sudo

要更改正确的输入,请参阅此处 How do I use .take on FirebaseListObservable?

答案 1 :(得分:0)

这有帮助吗?

loggedInUserId.subscribe(userId => { 
  var firebaseList = this.db.list(this.firebaseRoot.child(userId))
  // do stuff with the list
}

<强> 修改

switchMap是否会返回您需要的类型?

const firebaseList = 
  loggedInUserId.switchMap( userId => 
    this.db.list(this.firebaseRoot.child(userId))
  )

答案 2 :(得分:0)

您可以创建转换器

const mapToFirebaseListObservable = (source) => {
  new FirebaseListObservable(observer => {
    return source.subscribe({
      next(x) { observer.next(x); },
      error(err) { observer.error(err); },
      complete() { observer.complete(); }
    })
  })
}

一起使用
var firebaseList = mapToFirebaseListObservable(
  loggedInUserId
    .flatMap((userId) => this.db.list(this.firebaseRoot.child(userId)))
)

我没有在完整的firebase安装上尝试过,所以你可能会在新建FirebaseListObservable时遇到错误,但是我已经尝试了一个带有附加功能的Observable

const newObservable = new Observable(observer => {
  ...
})
newObservable['myFn'] = () => 'from myFn'

并且该函数在输出中存在并可调用。

编辑:这似乎也有效

const toInner = (source) => {
  return source.operator && source.operator.project
    ? source.operator.project()
    : source
}

用法:

var firebaseList = toInner(
  loggedInUserId
    .flatMap((userId) => this.db.list(this.firebaseRoot.child(userId)))
)

它也可以变成一个链式运算符

const toInner = function() {
  const source = this
  return source.operator && source.operator.project
    ? source.operator.project()
    : source
}
Observable.prototype.toInner = toInner;

有关创建运算符的更改,请参阅here了解Rxjs v5.50beta。