Angular - '(error: any) => void'类型的参数不可分配给'() => void'类型的参数

时间:2021-06-07 21:51:44

标签: angular

我在 Angular-11 中得到了这个错误处理程序代码:

    return this.api.post('auth/user/login', data, headers).subscribe(
      (result: any) => {
        console.log(result.message);
        console.log(result.code);
        if (result.error === 'true' ){
          console.log(result.message);
        }
      },            
          data => this.tokenHandler(data),
          error => this.errorHandler(error.error)
     );
    }


    errorHandler(error: any){
      this.notify.clear();
    //  console.log(error);
      if (error.errors && error.errors.username){
        this.error = error.errors.username;
      }
      else if (error.message === 'Unauthorized'){
        this.error = null;
        this.notify.error('Invalid Login Details or email not confirmed', {timeout: 0})
      } else {
        this.error = null;
        this.notify.error(error.message, {timeout: 0})
      }
    }

但它导致了这些错误:

Error: src / app / auth.component.ts: 84: 11 - error TS2769: No overload matches this call.
The last overload gave the following error.
Argument of type '(error: any) => void'
is not assignable to parameter of type '() => void'.

84 error => this.errorHandler(error.error) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules / rxjs / internal / Observable.d.ts: 54: 5
54 subscribe(next ? : (value: T) => void, error ? : (error: any) => void, complete ? : () => void): Subscription;
~~~~~~~~~
The last overload is declared here.


Error: src / app / auth.component.ts: 84: 11 - error TS7006: Parameter 'error'
implicitly has an 'any'
type.

84 error => this.errorHandler(error.error)

这一行突出显示:error => this.errorHandler(error.error)

如何解决?

谢谢

2 个答案:

答案 0 :(得分:1)

这就解释了subscribe(next ? : (value: T) => void, error ? : (error: any) => void, complete ? : () => void): Subscription;

您正在向 subscribe 传递三个参数(回调),是的。但是,您的第三个回调(错误处理程序)与上述函数定义的第三个参数不匹配。它接受一个没有参数的回调作为第三个参数。

相反,看起来第一个回调应该从结果中获取令牌 (result.data?) 并在那里调用 this.tokenHandler,第二个回调应该是您的错误处理程序。基本摆脱data => this.tokenHandler(data),

答案 1 :(得分:0)

在我看来,errorHandler 被调用时没有参数。也许传递给它的错误没有 error 属性? (意思是 error.error 未定义?)