首页 > 解决方案 > Angular:对象不是 ApiService.saveData() 中的函数

问题描述

ApiService

正如您在此处看到的,saveData()方法将通过给定的 URL 访问后端服务器,但如果后端服务器抛出任何错误,我应该向用户显示该错误,因为我编写了handleError()方法并通过管道运算符调用,即catchError(this.handleError)这一行抛出TypeError: Object is not a function

请给任何建议。

代码片段:

import { Observable, throwError} from 'rxjs';
import {catchError} from 'rxjs/operators';
            
  @Injectable({
    providedIn: 'root'
  })

  export class ApiService {

  public  saveData(url,Object):Observable<any>{
      return this.http.post(url,Object).pipe(catchError(this.handleError));
    }

    handleError(errorResponse:HttpErrorResponse){
      console.log('handleerror')
      return throwError(errorResponse.message || 'server error');
    }
    
  }

错误

如您所见,这是我在控制台中发现的错误:

core.js:6157 ERROR TypeError: Object is not a function
    at ApiService.saveData (api.service.ts:18)
    at new-channel.component.ts:66
    at SafeSubscriber.schedulerFn [as _next] (core.js:25910)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at EventEmitter_.next (Subject.js:39)
    at EventEmitter_.emit (core.js:25879)
    at ConfirmModalComponent.Passback (confirm-modal.component.ts:30)

标签: javascriptangular

解决方案


您需要提供一个错误函数才能使用 catchError 方法。

看这里:

在此处输入链接描述

.pipe(catchError(err => this.yourErrorHandler(err)))

推荐阅读