简体   繁体   中英

CanActivate don't display the desired component when the returned result is true

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 { }

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM