问题描述
编写此代码时,IDE显示错误.
IDE shows error when I write this code.
我有一个组件,该组件在ngOnInit中调用service来获取数据.服务调用另一个服务来获取一些数据,并使用它来获取数据,然后将其返回.
I have a component that calls service in ngOnInit to get the data. Service calls the other service to get some data and use it to get data then returns it.
组件:
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,源,运算符,提升和另外6个."
I've got this error: "Type 'Subscription' is missing the following properties from type 'Observable': _isScalar, source, operator, lift, and 6 more."
推荐答案
subscribe
不是与 then
等效的rxjs.具体来说,使用诺言,您可以执行 somePromise.then(doSomething).then(doSomethingElse)
,但不能进行 someRxjsStream $ .subscribe(doSomething).subscribe(doSomethingElse)
.如果要转换数据流,则应使用几种可用的rxjs运算符之一,在本例中为 map
:
subscribe
is not a rxjs equivalent of then
. Specifically, with promises you can do somePromise.then(doSomething).then(doSomethingElse)
, but you can't someRxjsStream$.subscribe(doSomething).subscribe(doSomethingElse)
. If you want to transform the data stream, you should use one of several available rxjs operators, and in your case it's 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));
}
这篇关于类型“订阅"缺少以下属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!