将函数转换为可观察的

Convert function into observable

任何人都可以帮助使这个函数成为可观察的吗?我需要用它来根据查询检查文档是否已经存在。我需要订阅它,这样如果没有我可以创建一个文档。

目前它给我一个错误:

A function whose declared type is neither 'void' nor 'any' must return a value.

    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
    }
});

您应该 pipe 通过 map 结果而不是订阅,因为您希望将结果转换为布尔值。

其次,编译器抱怨是因为您提供了 return 类型,但实际上并没有 return 任何东西,因此请确保您 return 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()