Ionic 4 在从 http 请求调用返回的对象键上抛出错误

Ionic 4 throwing errors on object keys returned from a http request call

所以我有这样的功能

if (form.valid) {
      this.api.resetPassword(this.otpcode).subscribe(response => {
        if (response.success) {
          this.showToast(response.message);
          this.router.navigateByUrl("/login");
        }
        if (response.error) {
          this.showToast(response.error);
        } else {
          this.errors = response.errors;
        }
      });
    }
  }

但是在 VS Code 中,我在尝试获取响应的行中遇到错误,例如 response.success 表示 Property 'success' does not exist on type 'Object | any[]'. Property 'success' does not exist on type 'Object'.ts(2339)。 我认为这只是一个 VS Code 错误,甚至在 运行 ionic cordova build 之后控制台中也会出现相同的错误。

所以我所做的是首先添加一个导出变量并在尝试访问属性之前将响应传递给它。

export class ForgotPasswordPage implements OnInit {
  response: any;
     ......
}

那我就

onVerify(form: NgForm) {
    this.submitted = true;

    if (form.valid) {
      this.api.resetPassword(this.otpcode).subscribe(response => {
        this.response = response;
        if (this.response.success) {
          console.log(response);
          this.showToast(this.response.message);
          this.router.navigateByUrl("/login");
        }
        if (this.response.error) {
          this.showToast(this.response.error);
        } else {
          this.errors = this.response.errors;
        }
      });
    }
  }