Search code examples
typescriptionic-frameworkionic4

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


So I have this function like this

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;
        }
      });
    }
  }

However in VS Code I get an error on the lines trying to get the response e.g response.success that says Property 'success' does not exist on type 'Object | any[]'. Property 'success' does not exist on type 'Object'.ts(2339). I thought it was just a VS Code error and even after running ionic cordova build the same error appears in the console.


Solution

  • so what I did was first to add an exported variable and pass the response to it before trying to access the properties.

    i.e

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

    then I do

    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;
            }
          });
        }
      }