如何解决为什么在执行 RxJS tap() 运算符后尝试订阅 Observable 时会出现此错误?
我正在使用 Firebase FireStore 数据库开发 Angular 应用程序,但在尝试使用 RxJS 时遇到了以下问题。我会试着向你解释我想要做什么。
我只是将这个服务方法定义到一个服务类中:
getPatientAesteticEvaluationData(patientUID): Observable<AestheticEvaluation> {
return this.firestore.collection('aesthetic-evaluation')
.doc(patientUID)
.valueChanges()
.pipe(
map(aestheticEvaluation => !!aestheticEvaluation ? aestheticEvaluation : {}),tap(console.log)
)
}
前面的方法应该从 FireStore 集合中检索数据(如果存在),将其作为 Observable 返回。
然后进入我正在做的组件代码:
ngOnInit(): void {
console.log("AestheticEvaluationComponent INIT");
//this.patientAestheticEvaluationData$ = this.patientService.getPatientAesteticEvaluationData(this.patientUID)
this.patientAestheticEvaluationData$ = this.patientService.getPatientAesteticEvaluationData(this.patientUID)
.pipe(
tap(aestheticEvaluationData => !!aestheticEvaluationData ? this.fillAestheticEvaluationForm(aestheticEvaluationData) : null),tap(console.log)
);
//this.patientAestheticEvaluationData$.subscribe();
}
我正在尝试调用之前的服务方法以检索返回的 Observable 对象。 然后我试图访问这个对象的内容,以便调用 fillAestheticEvaluationForm(aestheticEvaluationData) 将这些数据传递给它。
目前这是我的 fillAestheticEvaluationForm() 方法中唯一的代码:
fillAestheticEvaluationForm(aestheticEvaluationData) {
console.log("fillAestheticEvaluationForm START !!! aestheticEvaluationData: ",aestheticEvaluationData);
}
问题在于,以这种方式执行此方法从未被调用。我认为我必须订阅返回的 observable 但如果我尝试这样做:
this.patientAestheticEvaluationData$ = this.patientService.getPatientAesteticEvaluationData(this.patientUID)
.pipe(
tap(aestheticEvaluationData => !!aestheticEvaluationData ? this.fillAestheticEvaluationForm(aestheticEvaluationData) : null),tap(console.log)
).subscribe();
我在 this.patientAestheticEvaluationData$ 上得到一个错误:
ERROR in src/app/features/patient/patient-details/aesthetic-evaluation/aesthetic-evaluation.component.ts:24:5 - error TS2740: Type 'Subscription' is missing the following properties from type 'Observable<AestheticEvaluation>': _isScalar,source,operator,lift,and 6 more.
24 this.patientAestheticEvaluationData$ = this.patientService.getPatientAesteticEvaluationData(this.patientUID)
怎么了?我错过了什么?如何修复此代码?
解决方法
如果你订阅了 Observable,你返回的不再是 Observable 而是订阅,你需要在你的组件中订阅 Observable 或者干脆什么都不返回并声明返回类型为 void。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。