Angular 9 Type any [] |无法将ReceiptResponse分配给类型

问题描述 投票:0回答:1

我正在使用HttpClient通过服务从JSON api检索记录。我创建了一个类,该类相同地表示从api返回的对象,但是,出现以下错误。

Type 'any[] | ReceiptResponse' is not assignable to type 'ReceiptResponse'

我的服务具有以下功能:

getPagedReceipts(
  filter = '',
  sortOrder = 'ASC',
  sortColumn = 'receipt.id',
  pageNumber = 0,
  pageSize = 5,
): Observable<ReceiptResponse> {
     return this.http.get<ReceiptResponse>(this.baseUrl, {
       params: new HttpParams()
         .set('filter', filter)
         .set('sortOrder', sortOrder)
         .set('sortColumn', sortColumn)
         .set('pageNumber', pageNumber.toString())
         .set('pageSize', pageSize.toString())
     }).pipe(
       catchError(this.handleError)
     );
}

我在以下函数中称呼它。

public receiptsResponse: ReceiptResponse;

this.receiptService.getPagedReceipts(filter, sortOrder, sortColumn,
  pageIndex, pageSize).pipe(
  catchError(() => of([])),
  finalize(() => this.loadingSubject.next(false))
).subscribe(receiptsResponse => {
  this.receiptsResponse = receiptsResponse; <-- this is location of the error.
  this.receipts = this.receiptsResponse.items; 
  console.log(this.receiptsResponse);
  this.receiptsSubject.next(this.receipts);
});

这是收据响应:

import {Receipt} from './receipt';

export class ReceiptResponse {
  public itemCount: number;
  public items: Receipt[];
  public next: string;
  public pageCount: number;
  public previous: string;
  public totalItems: number;


  constructor(
    itemCount?: number,
    items?: Receipt[],
    next?: string,
    pageCount?: number,
    previous?: string,
    totalItems?: number

  ) {
    this.itemCount = itemCount;
    this.items = items;
    this.pageCount = pageCount;
    this.next = next;
    this.previous = previous;
    this.totalItems = totalItems;
  }
}
angular typescript
1个回答
0
投票

这是因为您的catch块返回了一个可观察到的空数组

catchError(() => of([])),

尝试返回null代替

catchError(() => of(null)),
© www.soinside.com 2019 - 2024. All rights reserved.