【问题标题】:Angular2 Http with RXJS Observable TypeError: this.http.get(...).map(...).catch is not a function带有 RXJS Observable TypeError 的 Angular2 Http:this.http.get(...).map(...).catch 不是函数
【发布时间】:2016-11-20 10:01:55
【问题描述】:

我有以下服务一直运行良好,直到今天我收到此错误

TypeError: this.http.get(...).map(...).catch is not a function. 

当我调试这段代码时,它在涉及到 catch 方法时会崩溃。

import { Test } from "./home.component";
import { Injectable }     from "@angular/core";
import { Inject } from "@angular/core";
import { Http , Response  } from "@angular/http";
import { Observable }     from "rxjs/Observable";

@Injectable()
export class HomeService {
   public constructor(@Inject(Http)  private http: Http) {}

   public getData (): Observable<Test []> {
        return this.http.get("./src/app/home/home-data.json")
            .map(this.extractData).catch(this.handleError);
    }

    public extractData(res: Response) {
        let body = res.json();
        return body.data || { };
    }

    public handleError (error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We"d also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : "Server error";
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
  }

【问题讨论】:

    标签: typescript angular rxjs


    【解决方案1】:

    “rxjs/Observable”中的“O”字符必须是大写

    将它指定为小写“o”,会给您这个和其他令人毛骨悚然的错误。 这必须像这样导入:

    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';
    

    我花了一个小时才找到它。 使用 import 时,名称通常为小写。 这是我第一次看到这个。 我希望它会帮助其他人:)

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,但就我而言,问题是,我在 Module.ts 中多次导入了必需的模块

      【讨论】:

        【解决方案3】:

        catch 操作符好像没有导入。

        您可以尝试像这样导入它:

        import 'rxjs/add/operator/catch'
        

        或者更一般地说,如果您想为可观察对象提供更多方法:

        import 'rxjs/Rx';
        

        看到这个问题:

        【讨论】:

        • 成功了!谢谢。我的供应商文件中有这个import 'rxjs/Rx 真是太疯狂了,我在该文件中也为 angular2 导入了我的其他依赖项,但我相信我需要将此库导入到我想使用它的每个文件或 main.ts 中。跨度>
        • @Thierry,显然导入整个 rxjs/Rx 不是一个好习惯。你认为只导入你需要的操作符不是很大的改进吗?
        猜你喜欢
        • 2017-10-13
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 2021-12-03
        • 2020-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多