0

我有以下 API 函数:

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

此功能将检查 JWT 是否存在,然后如果登录的用户是管理员,则让他浏览不同的组件。

下面,是 canActivate 方法。我为它创建了一个新服务,并将它包含在 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'])
    }
  }


}

当登录的用户是管理员时,PHP 返回 true,如果不是这种情况,则返回 false,但forgot如果它是 true,则它们没有重定向到调用的组件。甚至在组件为假时也没有重定向login

这是我的路线:

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

1 回答 1

0

更改checkLoggedInAdmin函数以返回 Observable。

在这里,我们使用 map 来转换结果,因此您还需要添加以下导入:

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

然后,只需修改canActivate以返回 observable

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) :Observable<boolean>
{
    return this.authApi.checkLoggedInAdmin();
}
于 2018-07-16T13:05:41.323 回答