使用PHP在Angular2中设置自定义AuthGuard

时间:2018-04-05 07:57:17

标签: php angular angular2-routing

我是Angular2的新手并且正在学习。

这是我项目中的文件夹结构。

Java

这是我的 app.adminroute.ts 文件: -

var/www/html/
        |_(angproject)
                |_(phpscript)
                |       |_login.php
                |_(src)
                   |_(app)
                        |_(admin)
                        |   |_(login)
                        |   |   |_login.component.ts
                        |   |
                        |   |_admin.component.ts
                        |
                        |_(_admin_service)
                        |       |_admin.login.ts
                        |
                        |_(_animations)
                        |
                        |_(front)
                        |
                        |_(_models)
                        |   |_admin.model.ts
                        |
                        |_(_authguard)
                        |   |_adminauth.guard.ts
                        |
                        |_app.adminroute.ts
                        |_app.module.ts

在我的 login.component.ts 文件中,我将管理员的 id 存储在localstorage中: -

import { RouterModule, Routes } from '@angular/router';
import { APP_BASE_HREF } from '@angular/common';
import { CanActivate } from "@angular/router";

import { AdminComponent } from './admin/admin.component';
import { LoginComponent } from './admin/login/login.component';
import { DashboardComponent } from './admin/dashboard/dashboard.component';

import { AdminAuthGuard } from './_authguard/adminauth.guard';


export const appAdminRoutes: Routes = [
  { path: 'admin',
    component: AdminComponent,
    children: [
          { path: '', component: LoginComponent},
          { path: 'dashboard', component: DashboardComponent, canActivate: [AdminAuthGuard] }
    ]
  }
];

这是我的 adminauth.guard.ts 文件: -

submitPost()
  {        
      this._adminLogin.postAdminLogin(this.adminLoginmodel).subscribe(
          data => {
                this.responseStatus = data;
                if(this.responseStatus.status == 1)
                {
                  localStorage.setItem('admin_id', this.responseStatus.detail.id);
                  //console.log(localStorage.getItem("admin_id"));
                  this.router.navigate(['admin/dashboard'])
                }
                else
                {
                  alert('Login Error');
                }
              },
          err => {
                console.log(err)
              },
          () => {}
      ); 
      this.status = true;       
  }

函数import { Http, Response, Headers, RequestOptions} from '@angular/http'; import { HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/share'; @Injectable() export class AdminAuthGuard { http : Http; actionUrl : string; admin_auth_Url: string; adminAuthResponse:Object= []; constructor(public _http: Http) { this.http = _http; this.admin_auth_Url = 'http://localhost/angproject/phpscript/isadminlogin.php'; } checkAdminAuth() { let headers = new Headers(); headers.append("Accept", "q=0.8;application/json;q=0.9"); this.actionUrl = this.admin_auth_Url; return this.http.post(this.actionUrl, {admin_id:localStorage.getItem("admin_id")}, { headers: headers }) .map(res => res.json()).share(); } } 调用一个php文件,它以下列方式返回响应数据: -

checkAdminAuth()

每当我尝试访问仪表板页面时, checkAdminAuth()函数必须点击php文件来检查身份验证。如果响应状态为 0 ,则会重定向到{"status":0,"message":"Message comes here","error":} 。如果状态为 1 ,则应该导致http://localhost:4200/admin

如何触发checkAdminAuth函数来获取响应并执行重定向?

1 个答案:

答案 0 :(得分:1)

您的AdminAuthGuard应该实现CanActivate界面。它有一个方法canActivate,它应该包含checkAdminAuth中的内容。否则在路由时永远不会被调用。此外,canActivate应该返回BooleanPromise<Boolean>Observable<Boolean>,因此您应该将结果映射为返回结果。

您希望获得的条件重新路由可以在AdminAuthGuard这样完成

canActivate() {
    if (/*user is logged in*/) {
        this.router.navigate(['/admin']);
        return true;
    }
    else {
        this.router.navigate(['/dashboard']);
    }
    return false;
}