TypeError:rxjs__WEBPACK_IMPORTED_MODULE_2 __。Observable.throw不是函数

时间:2018-05-30 10:36:00

标签: angular rxjs angular6

这是我的文件userdata.service.ts:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs';
import { map } from "rxjs/operators";
import { catchError } from 'rxjs/operators';
import { Data } from './userdata';

@Injectable()
export class UserDataService {

  url : "http://localhost:4200/assets/data/userdata.json";
  constructor(private http:Http) { }  

  getDataWithObservable() : Observable<any>{
      return this.http.get(this.url)
            .pipe(
              map(this.extractData),
              catchError(this.handleErrorObservable)
            );
  }

    private extractData(res: Response) 
    {
        let body = res.json();      
        return body;
    }

    private handleErrorObservable (error: Response | any) 
    {   
        return Observable.throw(error.message || error);
    }
}

我收到以下错误:

  

TypeError:rxjs__WEBPACK_IMPORTED_MODULE_2 __。Observable.throw不是   功能

3 个答案:

答案 0 :(得分:14)

导入:

import { throwError } from 'rxjs';

用法:

return throwError(err);

答案 1 :(得分:2)

Observable.throw() has been deleted.

尝试使用Observable.throwError()。显然,这些定义尚未更新。

您可以使用import { throwError } from 'rxjs';

导入它

答案 2 :(得分:0)

在Angular 8中使用

throwError(new NotFoundError("Resource Not Found."))

不使用

Observable.throw(new NotFoundError("Resource Not Found."))

完整示例

catchError((错误:响应)=> {

    if(error.status === 404){

      return throwError(new NotFoundError("Resource Not Found."));

    }

    return throwError(new AppError(error))

})