简体   繁体   English

RxJs catchError 更改返回类型

[英]RxJs catchError changes return type

I'm trying to implement some caching and I have the below method.我正在尝试实现一些缓存,并且我有以下方法。 The catchError block is causing an error because the return type becomes Observable<Client | Client[]> catchError块导致错误,因为返回类型变为Observable<Client | Client[]> Observable<Client | Client[]> . Observable<Client | Client[]> I'm not seeing why it thinks it's not an array of client, or how to fix.我不明白为什么它认为它不是一组客户端,或者如何修复。

#clients: Client[] = []
#clientsLastModified: string | null = null


index(): Observable<Client[]> {
    let headers = new HttpHeaders()
    if (this.#clientsLastModified)
        headers = headers.set('If-Modified-Since', this.#clientsLastModified)

    return this.http.get<IClientDTO[]>('clients', {headers, observe: 'response'}).pipe(
        map(x => {
            this.#clientsLastModified = x.headers.get('Last-Modified')

            if (x.status === HttpStatusCode.Ok && x.body) {
                this.#clients = x.body.map(x => new Client(x))
                return this.#clients
            } else
                return of([])
        }),
        catchError((err: unknown) => {
            if (err instanceof HttpErrorResponse && err.status === HttpStatusCode.NotModified)
                return this.#clients

            return throwError(() => err)
        })
    )
}

There are two small changes to make to get this corrected:为了纠正这个问题,需要做两个小改动:

  1. don't use of inside your map.不要在 map 内部使用of You want the result of your map to return type Client[] ;您希望 map 的结果返回类型Client[] of makes it return Observable<Client[]> of使其返回Observable<Client[]>

  2. use of inside catchError . of内部catchError Inside catchError , you should return observable, so of is needed.catchError中,你应该返回 observable,所以of是必需的。 The reason no error is shown is because the type is Array, and Array is also a vaild ObservableInput , but will have different behavior.没有显示错误的原因是因为类型是 Array,并且 Array 也是有效的ObservableInput ,但会有不同的行为。 RxJS will convert Array to an observable that emits each item individually ( thus the type ends up being Observable<Client> instead of Observable<Client[]> ). RxJS 会将 Array 转换为单独发出每个项目的 observable(因此类型最终是Observable<Client>而不是Observable<Client[]> )。

return this.http.get<IClientDTO[]>('clients', {headers, observe: 'response'}).pipe(
  map(x => {
    this.#clientsLastModified = x.headers.get('Last-Modified')

    if (x.status === HttpStatusCode.Ok && x.body) {
      this.#clients = x.body.map(x => new Client(x))
        return this.#clients
      } else
        return [] // <-- don't use of
  }),
  catchError((err: unknown) => {
    if (err instanceof HttpErrorResponse && err.status === HttpStatusCode.NotModified)
      return of(this.#clients) // <-- use of

      return throwError(() => err)
  })
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM