【问题标题】:What is the RXJS 6 way of handling http Observables?RXJS 6 处理 http Observables 的方式是什么?
【发布时间】:2019-10-28 02:47:39
【问题描述】:

我注意到我的代码在新项目中使用时不起作用:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

import { TypeAndCountURL } from '@app/constants';
import { HttpErrorService } from '@app/services/http-error.service';
import { TypeAndCountResponseBody, TypeAndCountRequestBody } from '@app/models/type-and-count/bodies.interface';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor (private http: HttpClient, private httpErrorService: HttpErrorService) {}

  postTypeAndCountRequest(typeAndCountRequestBody: TypeAndCountRequestBody): Observable<TypeAndCountResponseBody> {
    return this.http.post<TypeAndCountResponseBody>(TypeAndCountURL, typeAndCountRequestBody).pipe(
      catchError(this.httpErrorService.handleError<TypeAndCountResponseBody>('postTypeAndCountRequest'))
    );

  }
}

具体来说,我收到的是Cannot find name 'catchError'. Did you mean 'RTCError'?ts(2552)

阅读后,我发现我可以通过单独导入它来解决问题(从 rxjs/operators .. whihc 很好,但是).. 而且整个结构是 rxjs 5 的兼容模式 ... RXJS 6 处理错误响应的方式是什么?

【问题讨论】:

  • 从 rxjs 6 开始,所有算子都必须单独导入。从“rxjs/operators”导入 { catchError };
  • 我还需要使用它吗?我读到整个运营商都在弃用...
  • 您可以移除 catchError 运算符并在订阅级别处理错误。例如:myobservable.subscribe(result=>{...do something},error=>{...handle error})

标签: javascript angular typescript ecmascript-6 rxjs


【解决方案1】:

你可以使用

import { catchError } from "rxjs/operators";

fetchUser() {
       this.userService.getProfile()
          .subscribe(
             (data: User) => this.userProfile = { ...data }
              , // success path
              error => this.error = error // error path
       );
    }

【讨论】:

  • 我在我的 OP 中指出,我知道我可以做到这一点,但这在其他地方被描述为一种“旧”的做法。我正在寻求新的方式。
  • @robertotomás 再次检查我的答案。你可以像我一样处理错误。第一个回调将是结果,第二个回调将是错误处理程序
  • 嘿,托尼,我再次感谢你的回答——我注意到它正在变得流行 :) 你可能想修改它以淡化旧的方式,因为那不是你的帖子。最佳
猜你喜欢
  • 1970-01-01
  • 2020-04-22
  • 2021-02-18
  • 2021-12-16
  • 1970-01-01
  • 2021-09-26
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多