“rxjs” observable.throw is not a function - Angular4

微笑、不失礼 提交于 2019-11-29 22:13:43
Alexander Staroselsky

The error There are multiple modules with names that only differ in casing. is indicating the wrong import is being targeted with how you are trying to use Observable.

The import should be with a capital "O" like:

import { Observable } from 'rxjs/Observable';

This will import the individual Observable operator, which be used in combination with operators such as catch or throw on created Observables.

import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

To import the full Observable object you'd import it like this:

import { Observable } from 'rxjs/Rx'

Hopefully that helps!

Update:

With newer versions of RxJS (5.5+) operators such as map() and filter() can used as pipeable operators in combination with pipe() rather than chaining. They are imported such as:

import { filter, map, catchError } from 'rxjs/operators';

Keep in mind terms such as throw are reserved/key words in JavaScript so the RxJS throw operator is imported as:

import { _throw } from 'rxjs/observable/throw';

Update:

For newer versions of RxJS (6+), use this:

import { throwError } from 'rxjs';

and throw an error like this:

if (error.status === 404)
    return throwError( new NotFoundError(error) )

In RxJS 6, Observable.throw() is replaced by throwError() which operates very similarly to its predecessor. So, you can replace from Observable.throw(error) to only throwError(error) by importing:

import { throwError } from 'rxjs';

Checkout this link for further reference: https://www.metaltoad.com/blog/angular-6-upgrading-api-calls-rxjs-6

I was facing the same issue in my angular 5 application. What I did is, adding a new package.

import { throwError } from 'rxjs';
import { filter, map, catchError } from 'rxjs/operators';

And from my http service call I return a function.

return this.http.request(request)
      .pipe(map((res: Response) => res.json()),
        catchError((res: Response) => this.onError(res)));

And in onError function I am returning the error with throwError(error).

onError(res: Response) {
    const statusCode = res.status;
    const body = res.json();
    const error = {
      statusCode: statusCode,
      error: body.error
    };
    return throwError(error);
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!