“rxjs”observable.throw不是函数 - Angular4

时间:2017-08-02 15:20:50

标签: angular rxjs observable throw

我一直在学习Angular 4,一切顺利,直到我尝试在服务中实现catch处理。我正在尝试使用“rxjs”catch并抛出,但我的控制台中有一个未定义的函数错误。

import { Injectable } from '@angular/core';
import { Http } from "@angular/http";
import { Observable } from 'rxjs/observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { AppError } from "../app/common/app.error";
import { NotFoundError } from "../app/common/not-found-error";
import { BadInput } from "../app/common/bad-input";

@Injectable()
export class PostService {
  private url = "https://jsonplaceholder.typicode.com/posts";

  constructor(private http: Http) { }

 deletepost(post){
      // return this.http.delete(this.url + '/' + post.id)
      // Hard-coded id to test 404
      return this.http.delete(this.url + '/' + 93498)
        .catch((error: Response) => {
          console.log('error within catch is ' + Response)
          if(error.status === 404)
            return Observable.throw(new NotFoundError(error));

          return Observable.throw(new AppError(error));
        });
    }
}

这是错误消息:

TypeError: __WEBPACK_IMPORTED_MODULE_2_rxjs_observable__["Observable"].throw is not a function. 
(In '__WEBPACK_IMPORTED_MODULE_2_rxjs_observable__["Observable"].throw(new 
__WEBPACK_IMPORTED_MODULE_6__app_common_not_found_error__["a" /* NotFoundError 
*/](error))', 
'__WEBPACK_IMPORTED_MODULE_2_rxjs_observable__["Observable"].throw' is 
undefined) — post.service.ts:42

我的浏览器中也有此警告:

./~/rxjs/Observable.js
There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
* /Users/nickgowdy/Desktop/Angular2/angular4 source code/hello-world/node_modules/rxjs/Observable.js
    Used by 14 module(s), i. e.
    /Users/nickgowdy/Desktop/Angular2/angular4 source code/hello-world/node_modules/@angular/core/@angular/core.es5.js
* /Users/nickgowdy/Desktop/Angular2/angular4 source code/hello-world/node_modules/rxjs/observable.js
    Used by 1 module(s), i. e.
    /Users/nickgowdy/Desktop/Angular2/angular4 source code/hello-world/node_modules/@ngtools/webpack/src/index.js!/Users/nickgowdy/Desktop/Angular2/angular4 source code/hello-world/src/services/post.service.ts

5 个答案:

答案 0 :(得分:91)

错误There are multiple modules with names that only differ in casing.表示错误导入的目标是您尝试使用Observable的方式。

导入应使用大写“O”,如:

import { Observable } from 'rxjs/Observable';

这将导入单个Observable运算符,该运算符与已创建的Observables上的catchthrow等运算符结合使用。

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

要导入完整的Observable对象,您可以像这样导入它:

import { Observable } from 'rxjs/Rx'

希望这有帮助!

<强>更新

对于较新版本的RxJS(5.5+),map()filter()等运算符可以与pipe()结合使用pipeable operators而不是链接。它们是导入的,例如:

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

请注意,throw等术语是JavaScript中的保留/关键字,因此RxJS throw运算符导入为:

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

<强>更新

对于较新版本的RxJS(6+),请使用:

import { throwError } from 'rxjs';

并抛出这样的错误:

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

答案 1 :(得分:17)

在RxJS 6中,Observable.throw()throwError()取代,其运行方式与其前身非常相似。 因此,您可以通过导入以下内容将Observable.throw(error)替换为throwError(error)

import { throwError } from 'rxjs';

查看此链接以获取更多参考:https://www.metaltoad.com/blog/angular-6-upgrading-api-calls-rxjs-6

答案 2 :(得分:11)

我在angular 5应用程序中遇到了同样的问题。我所做的就是添加一个新程序包。

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

然后从我的http服务调用中返回一个函数。

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

onError函数中,我用throwError(error)返回错误。

onError(res: Response) {
    const statusCode = res.status;
    const body = res.json();
    const error = {
      statusCode: statusCode,
      error: body.error
    };
    return throwError(error);
  }

答案 3 :(得分:2)

_throw已在较新版本的RxJS中丢弃
对于RxJS(6+)的较新版本,请使用以下命令:

 import { throwError } from 'rxjs'; 

并抛出这样的错误:

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

答案 4 :(得分:0)

在Angular9中可观察到:

  1. 如果数据到达并且状态为OK,则发送数据
  2. 如果数据状态不正确,则引发错误
myObsFunc(): Observable<any> { 
  return this.http.get<any>('/api/something') 
    .pipe(
      /* Catch a backend error and let the component know */
      catchError( err => {
        /* Rethrow error */
        return throwError( err );
      }),
      map( (res)=> {
        if( res.STATUS == "OK" ) {
          /* Send DATA to subscriber */
          return Object.values( res.DATA)
        } else {
           /* Inform subscriber that a functional error occured */
           throw ( "getOrphans: Status is not OK but "+ res.STATUS ) ;
        }   
      }),
    )   
}