【问题标题】:Type 'Subscription' is missing the following properties from type 'Observable<StringMap<any>>'类型“订阅”缺少类型“可观察<StringMap<any>>”中的以下属性
【发布时间】:2020-01-03 17:32:25
【问题描述】:

错误:类型“订阅”缺少以下属性 输入“Observable>”:_isScalar、源、运算符、升降机、 还有 6 个.ts(2740)

这里我附上了我的代码。

在这里,在我的例子中,我有两个方法可以返回一个 observable,但是 getByTypeData 和 getByType。但是,从 getByTypeData() 返回 this.getByType(type).. 时,我遇到了上述错误。

P.S.:我想在我的组件中订阅 getByTypeData,它应该返回一个 observable。而且我是 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);
    }

【问题讨论】:

  • 你说你会返回一个 observable,但返回的是一个订阅。不要那样做。
  • 嗨@jonrsharpe,你能详细解释一下吗。可能是通过我的代码?谢谢。
  • 好吧,当你写 : Observable&lt;stringMap&lt;any&gt;&gt; 时,这意味着 “这个函数将返回一个 observable”,但随后 return this.getByType(type).subscribe(...) 返回一个 subscription,它不是可观察的。要么改变你说你要返回的东西,要么改变你正在返回的东西。

标签: javascript angular rxjs observable subscription


【解决方案1】:

正如 cmets 中所指出的,您返回的是 Subscription,而不是返回 Observable。我建议您阅读documentation 以了解它们之间的区别。

在您的特定情况下,我建议您尝试以下方法:

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 是一个 rxjs 运算符,需要使用如下语句导入:

import { switchMap } from 'rxjs/operators'
  • 可以在here找到有关此运算符的文档
  • 解释映射运算符的好文章是here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2022-01-03
    • 2021-06-24
    • 2019-06-02
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多