Search code examples
angulartypescriptstrapi

Angular strapi registration log only success message


I have simple registration method like this.

  register(
    firstName: string,
    lastName: string,
    email: string,
    password: string
  ) {
    const url = `${this.localAuthApiUrl}/register`;
    const username = email;
    const payload = {
      username,
      email,
      password,
      firstName,
      lastName,
    };

    return this.http.post<any>(url, payload).pipe(
      map((response: any) => {
        if (response.jwt) {
          console.log(response.jwt);
          return true;
        } else {
          console.log('FAIL');
          return false;
        }
      })
    );
  }

And using it like this

  register() {
    this.authenticationService
      .register(
        this.registerForm.value.registerFirstName,
        this.registerForm.value.registerLastName,
        this.registerForm.value.registerEmail,
        this.registerForm.value.registerPassword
      )
      .subscribe((value) =>
        value === true
          ? this.router.navigateByUrl('/')
          : console.log('Login failed')
      );
  }

Problem is that console.log works only in success case. But no log is printed in console on fail. so console.log('Login failed') console.log('FAIL'); is not printed but i can still see error message from strapi backend in console.


Solution

  • Try catchError operator.

    return this.http.post<any>(url, payload).pipe(
      map((response: any) => {
        if (response.jwt) {
          console.log(response.jwt);
          return true;
        } 
      }),
      catchError((error: any) => {
        console.log('FAIL');
        return of(false);
      })
    );