Home > Software engineering >  How to get a boolean based on http request status code in Angular 11
How to get a boolean based on http request status code in Angular 11

Time:04-30

I´m really lost in Angular 11 between all possibilities : Observable, Promise, Subscribe...

I would like just from a get api call a boolean response base on status code. This call is just to check if the token is already correct to redirect or not the user.

This is one of attempt:

export class AuthGuard implements CanActivate {
   constructor(private authService: AuthService, private router: Router, private userService: UserService ) {}
   async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if ( route.url.toString() === 'modifyPassword' ) {
      const resp = this.userService.canModifyPassword( route.queryParams.username, route.queryParams.token );
    } else {
      //
    }
  }
} 

export class UserService {
    constructor(private httpClient: HttpClient) {}
    
    canModifyPassword( username: string, token: string ): Observable<boolean> {
      return this.httpClient.get<HttpResponse<boolean>>(`${API_URL}/users/public/verify/${username}/${token}` );
  }

}

Someone has got the easiest and standardest solution in Angular 11 ?

CodePudding user response:

According to the Angular docs, you can read the full response by adding { observe: 'response' } to your get() method options object.

In your case, that would look like,

this.httpClient.get<HttpResponse<boolean>>(`${API_URL}/users/public/verify/${username}/${token}`, { observe: 'response' });

This will return an observable of type HttpResponse instead of just the body.

Then you can access the status code with response.status.

CodePudding user response:

The easiest way, IMO, is to convert a promise and await, like so:

 const resp = await this.userService.canModifyPassword( route.queryParams.username, route.queryParams.token ).toPromise();
    
console.log('got a response of', resp);

CodePudding user response:

I found finally a response. It is based on Promise like @E.Maggini response.

export class AuthGuard implements CanActivate {
   constructor(private authService: AuthService, private router: Router, private userService: UserService ) {}
   async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if ( route.url.toString() === 'modifyPassword' ) {
      const resp = await this.userService.canModifyPassword( route.queryParams.u, route.queryParams.t );
      if ( resp ) {
        return true;
      } else {
        await this.router.navigate(['/notAllowed'], {queryParams: {from: 'modifyPassword'}});
        return false;
      }
    } else {
      //
    }
  }
} 

export class UserService {
    constructor(private httpClient: HttpClient) {}
    
    async canModifyPassword(username: string, token: string): Promise<boolean> {
    return this.httpClient.get<any>(`${API_URL}/users/public/verify/${username}/${token}`).toPromise().then(
      data => {
        console.debug(data); // is null 
        return true;
      }).catch(err => {
        console.error(err);
        return false;
    });
  }

}
  • Related