Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Condition on Angular HHTP Request

Can you use conditions, with Angular subscribe function ?
Like, in this code :

   this.http.post<any>(phpUrl, content)
.subscribe(
    (r) => {
      if(r.message) // That's how the target script actually manages errors
      { 
        console.log(r.message);
        this.handleErrorPhp(r, formData.email);
      }
      else
      {
        this.router.navigate(['/login'], { queryParams: { register: true } });
      }
    },
    (error) => {
      this.handleErrorPhp(error, formData.email);
    }
  );

I’d like too navigate to the login page, when the script doesn’t catch any error. But, even when the "r.message" is empty, my code bugs and stops, telling me r.message is not defined.

EDIT : Here is the console error log :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ERROR TypeError: can't access property "message", i is null

>Solution :

I’d say check if r is defined before trying to access it’s property message. More info about the double-bang operator here.

this.http.post<any>(phpUrl, content).subscribe(
  (r: any) => {
    if (!!r && !!r.message) { 
      console.log(r.message);
      this.handleErrorPhp(r, formData.email);
    } else {
      this.router.navigate(['/login'], { queryParams: { register: true } });
    }
  },
  (error: any) => {
     this.handleErrorPhp(error, formData.email);
  }
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading