【问题标题】:Property 'subscribe' does not exist on type 'OperatorFunction<{}, {}>' error in Angular 7Angular 7 中的类型“OperatorFunction<{},{}>”错误中不存在属性“订阅”
【发布时间】:2019-07-06 15:56:22
【问题描述】:

在学习如何处理 Angular Typescript 中的错误时抛出了一个错误

“OperatorFunction”类型上不存在属性“订阅” 在我的组件的这个代码块中

createPost(post: HTMLInputElement) {
this.service.newPost(post).subscribe(
  response => {
    this.posts.splice(0, 0, post);
  },
  (error: AppError) => {
    if (error instanceof BadInput) {
      // Set form errors and display them next to input fields
      this.form.setErrors(error.originalError);
    } else {
      alert("An unexpected error occurred.");
      console.log(error);
    }
  }
);
}

组件代码使用的返回observable的服务代码是

newPost(post) {
return (
  this.http.post(this.url, post),
  catchError((error: Response) =>
    error.status === 400
      ? Observable.throw(new BadInput(error))
      : Observable.throw(new AppError(error))
  )
);
}

我需要帮助解决错误并解释为什么会抛出错误或如何最好地处理错误。

【问题讨论】:

  • newPost 看起来完全不正确,您是否缺少.pipe?您使用的是逗号运算符,而不是实际将 catchError 应用于 observable。
  • 当我尝试使用 .catchError 将 catchError 应用于可观察对象时,即使我有 import { Observable } from "rxjs"; ,我也会收到此错误 Property 'catchError' does not exist on type 'Observable&lt;Object&gt;'.
  • 然后读github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/…,因为看起来你已经习惯了pre-6的做事方式,但坚持一个随机的逗号是没有用的。
  • 好的,我现在就读这个
  • 您需要使用 .pipe() 然后将 catchError 放入其中,就像您打盹或过滤但没有点一样。因此,如果您在管道中有其他方法,逗号将是正确的。

标签: javascript angular


【解决方案1】:

您应该使用管道运算符,然后是 map 运算符,然后是 catchError 运算符。您必须从 rxjs/operators 导入 map 运算符和 catchError 运算符。请看下面:

.pipe(
    mergeMap(resp => {
        // add logic
    }),
    catchError(err => {
        // add handling 
    })
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2018-01-29
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    相关资源
    最近更新 更多