1

This Auth guard not working with API response. When I run the code it always returns true. but I want to run guard base on api response. is their way to achieving that?

import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route} from '@angular/router';
import {
    HttpClient,
    HttpHeaders
} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router, private http: HttpClient) {
    }

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        const sendData = {};
        sendData['id'] = sessionStorage.getItem('id');
        console.log(JSON.stringify(sendData));
        const headers = new HttpHeaders()
            .set('Content-Type', 'application/json')
            .set('token', sessionStorage.getItem('auth') ? sessionStorage.getItem('auth') : 'test');
        this.http.post('http://127.0.0.1:5000/auth',
            JSON.stringify(sendData), {
                headers
            })
            .subscribe(
                (val: any) => {
                },
                response => {

                    this.router.navigate(['/login']);
                },
                () => {
                    console.log('The POST observable is now completed.');
                });

        return true;

    }

}
Supun Abesekara
  • 708
  • 7
  • 32

1 Answers1

0

enter image description here

Check this. You have returned true at the end of the canActivate authguard. This way it will always return true. Instead you should have it in the subscribe method of the http post request based on your condition. Something like this..

this.http.post('http://127.0.0.1:5000/auth',
JSON.stringify(sendData), {
    headers
}).pipe(map(response => {
    //suppose we get isAuthenticated bit in response. Your response obj may vary but logic shall be same
    if (response.isAuthenticated) {
        return true;
    }
    else {
        return false;
    }
}));

Thanks.

Obaid
  • 2,563
  • 17
  • 15
  • Good Sir how I delay canActivate return. because API call gets some time to respond. – Supun Abesekara Mar 30 '19 at 05:09
  • As canActivate can return an Observable or Promise you don't need to worry about delay. If at all you want, you can hook to subscribe method of http post. – Obaid Mar 30 '19 at 09:43