【问题标题】:Angular 8 upgrade - typescript error - Type 'Observable<XYZ | Observable<any>>' is not assignable to type 'Observable<XYZ>'Angular 8 升级 - 打字稿错误 - 类型 'Observable<XYZ | Observable<any>>' 不可分配给类型 'Observable<XYZ>'
【发布时间】:2020-04-27 11:17:48
【问题描述】:

我有一个完美运行的代码(并且仍然完美运行)。当我从 angular 7 升级到 angular 8 时,我的 Visual Studio 代码开始显示 HttpClient.get 方法的错误。

错误出现在 HttpClient.get 方法的 catch 部分。代码编译良好并且工作正常。我检查了角度示例,一切看起来都正确。我不确定为什么编辑器显示问题。

     getLaborStats(dt: string, hotelId: string): Observable<LaborStats> {
    let lastDayLaborURL = HelloGMVars.varServiceURL + 'laborstats' ;
    const options = { headers: new HttpHeaders().append('AccessToken', this.accessToken)};
       return this.httpC.get<LaborStats>(lastDayLaborURL + '/' + hotelId + '/' + dt, options)
     .pipe(
        catchError(this.handleError('getLastDayLabor', null))
     );
     }

这是我的编辑器显示的错误 -

"[ts]
Type 'Observable<LaborStats | Observable<any>>' is not assignable to type 'Observable<LaborStats>'.
  Type 'LaborStats | Observable<any>' is not assignable to type 'LaborStats'.
    Type 'Observable<any>' is not assignable to type 'LaborStats'.
      Property 'today' is missing in type 'Observable<any>'.
(method) Observable<LaborStats>.pipe<LaborStats | Observable<any>>(op1: OperatorFunction<LaborStats, LaborStats | Observable<any>>): Observable<LaborStats | Observable<any>> (+10 overloads)
"

如果我删除 .pipe 部分,错误就会消失。所以,它告诉我 catchError 部分有问题。

这是我的错误处理程序 -

import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

import { Observable ,  of } from 'rxjs';

import { MessageService } from './message.service';
import { OktaAuthService } from './services/okta-auth.service';

/** Type of the handleError function returned by HttpErrorHandler.createHandleError */
export type HandleError =
  <T> (operation?: string, result?: T) => (error: HttpErrorResponse) => Observable<T>;

/** Handles HttpClient errors */
@Injectable()
export class HttpErrorHandler {
  constructor(private okta: OktaAuthService, private messageService: MessageService) { }

  /** Create curried handleError function that already knows the service name */
  createHandleError = (serviceName = '') => <T>
    (operation = 'operation', result = {} as T) => this.handleError(serviceName, operation, result);

  /**
   * Returns a function that handles Http operation failures.
   * This error handler lets the app continue to run as if no error occurred.
   * @param serviceName = name of the data service that attempted the operation
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  handleError<T> (serviceName = '', operation = 'operation', result = {} as T) {

    return (error: HttpErrorResponse): Observable<T> => {
      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      const message = (error.error instanceof ErrorEvent) ?
        error.error.message :
       `server returned code ${error.status} with body "${error.error}"`;

      // TODO: better job of transforming error for user consumption
      this.messageService.add(`${serviceName}: ${operation} failed: ${message}`);

      if (error.status === 401) {
        console.log('401 returned so logging out') ;
        this.okta.logout() ;
      }
      // Let the app keep running by returning a safe result.
      return of( result );
    };
  }
}

【问题讨论】:

    标签: angular typescript rxjs6 rxjs-observables


    【解决方案1】:

    验证您的错误处理策略。看起来您正在使用捕获和替换。 确保您的 handleError() 函数抛出如下错误:

      private handleError(error: HttpErrorResponse) {
        // Error handling here
        // rethrow
        throwError('Cannot perform the request, please try later');
      }
    

    从 RxJS 导入 throwError

    import { throwError } from 'rxjs';
    

    希望对你有帮助!

    【讨论】:

    • 添加了我的错误处理程序,它基于 Angular 网站上提供的参考。
    猜你喜欢
    • 2018-08-14
    • 2017-08-12
    • 2023-04-10
    • 2018-08-30
    • 2018-03-09
    • 2018-04-19
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    相关资源
    最近更新 更多