Type 'Subscription' is missing the following properties from type 'Observable<StringMap<any>>'

╄→гoц情女王★ 提交于 2020-04-16 02:39:53

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/57727125/type-subscription-is-missing-the-following-properties-from-type-observablest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!