当我写这段代码时,IDE显示错误。
我有一个组件,它调用ngOnInit中的服务来获取数据。服务调用另一个服务来获取一些数据,并使用它来获取数据,然后返回数据。
组件:
ngOnInit() {
const token = "abc";
this.service.getContactPersons(token).subscribe(
persons => this.contactPersons = persons
);
}服务:
getContactPersons(token: string): Observable<ContactPerson[]> {
return this.tokenService.getParameters(token).pipe(
switchMap((data: Params) => {
return this.http.get<Properties>(
this.baseUrl + `/abc/${data.param1}/properties/${data.param2}`
);
})
).subscribe((data: Properties) => data.contactPersons);
}我得到了这样的错误:“类型'Subscription‘缺少’Observable‘类型的以下属性:_isScalar、source、operator、lift以及更多。”
发布于 2019-10-08 15:14:53
subscribe不是then的rxjs等效项。具体地说,有了promises,你可以做somePromise.then(doSomething).then(doSomethingElse),但不能做someRxjsStream$.subscribe(doSomething).subscribe(doSomethingElse)。如果想要转换数据流,应该使用几个可用的rxjs操作符之一,在本例中是map
getContactPersons(token: string): Observable<ContactPerson[]> {
return this.tokenService.getParameters(token).pipe(
switchMap((data: Params) => this.http.get<Properties>(
`${this.baseUrl}/abc/${data.param1}/properties/${data.param2}`)),
map((data: Properties) => data.contactPersons));
}发布于 2019-10-08 14:57:34
您的函数getContactPersons返回一个订阅,就像现在一样。只需删除函数的.subscribe((data: Properties) => data.contactPersons);部分,它就可以做到这一点。
由于您将返回一个可观察对象,因此您应该始终尝试仅传递可观察对象本身或在pipe()中对其执行操作,并且只订阅一次,因为多个订阅可能会失控并导致内存泄漏,从而导致用户的性能损失。
https://stackoverflow.com/questions/58281451
复制相似问题