将函数转换为可观察的

时间:2018-07-22 00:17:25

标签: angular typescript rxjs google-cloud-firestore angularfire2

有人可以帮助将此功能设为可观察吗?我需要使用它来检查基于查询的文档是否已经存在。我需要订阅它,这样我才能创建一个文档。

当前它给我一个错误:

  

其声明类型既不是'void'也不是'any'的函数必须返回   一个值。

    exists(query: Vehicle): Observable<boolean>{
        this.afs.collection('vehicles',
            ref => 
            ref
            //queries
            .where("country","==", query.country)
          ).snapshotChanges().subscribe(
            res => {       

              if (res.length > 0){
                //the document exists
                return true
              }
              else {
                return false
              }
          }); 
    }//end exists()

然后我想称呼它

this.vehicleService.exists({country:"USA})
  .subscribe(x => {
    if (x) {
      //create a new doc
    }
});

1 个答案:

答案 0 :(得分:3)

如果要将结果转换为布尔值,则应通过pipe map Observable来代替结果。

第二,编译器在抱怨,因为您提供了返回类型,但实际上并未返回任何内容,因此请确保返回 exists(query: Vehicle): Observable<boolean> { return this.afs.collection('vehicles', ref => //queries ref.where("country", "==", query.country) ).snapshotChanges().pipe( // Use map to transform the emitted value into true / false map(res => res && res.length > 0) ) }//end exists()

它应该看起来像这样:

LinkedHashMap
相关问题