0

I have the following API function:

checkLoggedInAdmin():boolean
  {
    //Get the JWT token from local storage
    let jwt = localStorage.getItem('jwt');
    let httpParams = new HttpParams().set('jwt', jwt);
    let headerOptions = new HttpHeaders();
    headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    if(jwt=="" || jwt!=null)
    {
      this.http.post('http://dev.local/scripts/checkLoginAdmin.php', httpParams, {
        headers: headerOptions
      }).subscribe(
        (data)=>{
          if(data==true){
            return this.loggedIn = true;
          }
          else{
            return this.loggedIn = false;
          }
        },
        (error)=>{
          console.log(error)
        }

      )
    }
    else
    {
      this.loggedIn = false;
      return this.loggedIn;
    }
  }

This function, will check if a JWT exists, then if the user logged in is an admin, to let him navigate through different component.

The following, is the canActivate method. I created a new service for it, and include it at the app.module.ts:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthApiService } from './auth-api.service';
@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

  constructor(private router: Router, private authApi: AuthApiService) { }

  canActivate(route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot) :boolean
  { 
    if(this.authApi.checkLoggedInAdmin()==true)
    {
      return true;
    }
    else
    {
      //return false;
      this.router.navigate(['/login'])
    }
  }


}

The PHP is returning true when the user logging in is an admin, and false if it's not the case, but the their is no redirection, to the component called forgot if it is true. And even no redirection when it is false to login component.

Here is my routes:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { ForgotPasswordComponent } from './forgot-password/forgot-password.component';
import { AuthGuardService } from './auth-guard.service';

const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path:'',
    component: LoginComponent
  },

  {
    path: 'forgot',
    component: ForgotPasswordComponent,
    canActivate: [AuthGuardService]
  },
  {
    path: '**',
    redirectTo: 'login',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
alim1990
  • 4,656
  • 12
  • 67
  • 130

1 Answers1

0

Change the checkLoggedInAdmin function to return an Observable.

Here we're using map to transform the result, so you'll need to add the following imports as well:

import { map, tap } from 'rxjs/operators';
import { of, Observable } from 'rxjs';

  checkLoggedInAdmin():Observable<boolean>
  {
    //Get the JWT token from local storage
    let jwt = localStorage.getItem('jwt');
    let httpParams = new HttpParams().set('jwt', jwt);
    let headerOptions = new HttpHeaders();
    headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    if(jwt=="" || jwt!=null)
    {
      this.http.post('http://dev.local/scripts/checkLoginAdmin.php', httpParams, {
        headers: headerOptions
      }).pipe(
         tap(data => this.loggedIn = (data == true)),
         map(data => this.loggedIn)
      );
    }
    else
    {
      this.loggedIn = false;
      return of(false);
    }
  }

Then, simply modify the canActivate to return the observable

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) :Observable<boolean>
{
    return this.authApi.checkLoggedInAdmin();
}
user184994
  • 17,791
  • 1
  • 46
  • 52
  • @droidnation in what way? Are you getting an error, or is the behaviour not what you expected? – user184994 Jul 17 '18 at 05:44
  • I made a method to chekc the status of the variable `loggedIn` and it returned `undefined` even when user is logged in, so when I am setting it as true, it's not saving it, and can't know why. – alim1990 Jul 17 '18 at 06:01
  • Change the `map` function to set `this.loggedIn` before it returns `data == true` – user184994 Jul 17 '18 at 06:06
  • can you edit your answer for it. I think I am unable to access the variable and change it. Even though it was set at the beginning of the class. – alim1990 Jul 17 '18 at 06:15
  • @droidnation Try that. Please note that there is a new import there for `tap` – user184994 Jul 17 '18 at 06:19
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/176105/discussion-between-user184994-and-droidnation). – user184994 Jul 17 '18 at 06:32