Angular2使用RXJS Observable的Http出现TypeError: this.http.get(...).map(...).catch不是一个函数的错误。

13

我有以下服务,一直运作正常,但今天我遇到了这个错误

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);
    }
  }
3个回答

27

成功了!谢谢。真是太疯狂了,我在我的供应商文件中有这个 import 'rxjs/Rx,我还导入了其他依赖项,也适用于 Angular2,但我相信我需要在每个想要使用它的文件中或者在 main.ts 中导入此库。 - Jorawar Singh
@Thierry,显然导入整个rxjs/Rx并不是一个好的实践。你认为只导入你需要的操作符并没有太大的改进吗? - Adam Mendoza

0

我曾经遇到过同样的问题,但我的情况是,在Module.ts中多次导入了必需的模块。


0

'rxjs/Observable' 中的 'O' 字符必须是大写。

以小写字母 'o' 指定它,将会导致此类错误和其他神秘的错误。 必须像这样导入:

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

我花了一个小时才找到它。 通常在使用import时,名称都是小写的。 这是我第一次见到这个。 希望能对其他人有所帮助 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接