类型“订阅"缺少来自类型“Observable<StringMap<any>"的以下属性 [英] Type 'Subscription' is missing the following properties from type 'Observable<StringMap<any>>'
问题描述
错误:类型订阅"缺少以下属性输入'Observable>': _isScalar, source, operator, lift,还有 6 个.ts(2740)
这里我附上了我的代码.
在这里,就我而言,我有两种方法可以返回一个可观察对象,但是 getByTypeData 和 getByType.但是,在从 getByTypeData() 返回 this.getByType(type).. 时,我遇到了上述错误.
P.S.:我想在我的组件中订阅 getByTypeData,它应该返回一个 observable.我是 RXJS 的新手...
<预><代码>/*接口 IStringMap正如评论中指出的,您返回的是 Subscription
而不是 Observable
.我建议您阅读文档以了解它们之间的区别.
在您的特定情况下,我建议您尝试以下操作:
getByTypeData(type: string, ignoreApi = false): Observable>{如果(忽略Api){返回 this.handleConfig(type);}返回 this.getByType(type).pipe(开关映射(响应 => {const 配置 = response.result ?响应数据:{};返回 this.handleConfig(type, config);}));}
switchMap
是一个 rxjs 操作符,需要用这样的语句导入:
import { switchMap } from 'rxjs/operators'
ERROR : Type 'Subscription' is missing the following properties from type 'Observable>': _isScalar, source, operator, lift, and 6 more.ts(2740)
Here I have attached my code.
Here, in my case, I have two methods which return an observable, but getByTypeData and getByType. But, on returning this.getByType(type).. from getByTypeData() I am getting above error.
P.S.: I want to subscribe getByTypeData in my component which should return me an observable. AND I AM NEW TO RXJS...
/*
interface IStringMap<T> {
[index: string]: T;
}
*/
getByTypeData(type: string, ignoreApi = false): Observable<stringMap<any>> {
if (ignoreApi) {
this.handleConfig(type);
}
return this.getByType(type)
.subscribe(response => {
const config = response.result ? response.data : {};
return this.handleConfig(type, config);
});
}
// This method in another file (Just for reference)
getByType(type: string): Observable<stringMap<any>> {
return this.httpClient.get(`get url`);
}
handleConfig(type: string, config: stringMap<string | number> = {}): Observable<stringMap<any>> {
if (type === this.types) {
config.token = this.anotherservice.GetKey('mykey');
if (config.token) {
// logic
}
}
if (type === this.types) {
// logic
}
return of(config);
}
As pointed out in the comments, you are returning a Subscription
instead of returning an Observable
. I would suggest you read the documentation to get a good idea of the difference between them.
In your particular case, I would suggest you try something like the following instead:
getByTypeData(type: string, ignoreApi = false): Observable<stringMap<any>> {
if (ignoreApi) {
return this.handleConfig(type);
}
return this.getByType(type).pipe(
switchMap(response => {
const config = response.result ? response.data : {};
return this.handleConfig(type, config);
})
);
}
switchMap
is an rxjs operator that needs to be imported with a statement like this:
import { switchMap } from 'rxjs/operators'
- Documentation on this operator can be found here
- A good article explaining the mapping operators is here
这篇关于类型“订阅"缺少来自类型“Observable<StringMap<any>"的以下属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!