我已经构建了一个身份验证应用程序,可以从服务器接收用户信息和令牌(jwt)。我将数据存储在本地,然后用它在应用程序中进行更多计算。对于路由卫士,如果令牌可用,则应转到仪表板,否则返回登录。
这是我的身份验证服务,我正在调用loggingIn方法
import { HttpClient } from "@angular/common/http"
import { Router } from '@angular/router'
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private _registerUrl = "http://localhost:3000/api/register"
private _loginUrl = "http://localhost:3000/api/login"
constructor(private http: HttpClient, private _router:Router,private storage: Storage) { }
registerUser(user){
return this.http.post<any>(this._registerUrl,user)
}
loginUser(user){
return this.http.post<any>(this._loginUrl,user)
}
loggedIn(){
return !!this.storage.get('token')
}
getToken(){
return this.storage.get('token')
}
logoutUser(){
this.storage.remove('token')
this.storage.remove('user')
this._router.navigate(['/login'])
}
}
路由文件
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { DashboardPage } from './dashboard/dashboard.page';
import {HomePage } from './dashboardComponents/home/home.page'
import {MessagesPage } from './dashboardComponents/messages/messages.page'
import {PaymentsPage } from './dashboardComponents/payments/payments.page'
import {PostedJPage } from './dashboardComponents/posted-j/posted-j.page'
import {ProfileEditPage } from './dashboardComponents/profile-edit/profile-edit.page'
import {PostPage } from './dashboardComponents/post/post.page'
import {SettingsPage} from './dashboardComponents/settings/settings.page'
import { PasswordResetPage } from './password-reset/password-reset.page'
import { JobCompletedPage } from './dashboardComponents/job-completed/job-completed.page'
import { AppliedJobsPage} from './dashboardComponents/applied-jobs/applied-jobs.page'
import { AuthGuard } from './auth.guard'
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' },
{ path: 'register', loadChildren: './register/register.module#RegisterPageModule' },
{ path: 'password-reset', component:PasswordResetPage, pathMatch:'full' },
{ path:'dashboard', redirectTo:'dashboard/home/1000}'},
{ path:'dashboard', component: DashboardPage,canActivate: [AuthGuard],
children: [
{ path: 'messages', component:MessagesPage , pathMatch:'full'},
{ path: 'home/:distance', component: HomePage , pathMatch:'full'},
{ path: 'payments', component:PaymentsPage , pathMatch:'full'},
{ path: 'post', component:PostPage ,pathMatch:'full'},
{ path: 'settings', component: SettingsPage, pathMatch:'full' },
{ path: 'profile-edit', component: ProfileEditPage, pathMatch:'full' },
{path:'posted', component:PostedJPage,pathMatch:'full'},
{path:'job-completed', component:JobCompletedPage, pathMatch:'full' },
{path:'applied-jobs',component:AppliedJobsPage,pathMatch:"full"}
]
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
export const components = [
HomePage,
MessagesPage,
PaymentsPage,
PostedJPage,
ProfileEditPage,
DashboardPage,
PostPage,
SettingsPage,
PasswordResetPage,
JobCompletedPage,
AppliedJobsPage
];
保护文件
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree,CanActivate,Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService} from './auth.service'
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private _authService: AuthService, private _router:Router){
}
canActivate(): boolean {
if(this._authService.loggedIn()){
return true
} else {
this._router.navigate(['/login'])
return false
}
}
}
我正在使用离子存储,因为我最终会在Playstore上启动它。无论令牌是否存在,即使我对其进行了保护,它仍然会转到仪表板页面。
答案 0 :(得分:0)
尝试一下:
修改您的LoggedIn方法以返回承诺(删除!!)
loggedIn() {
return this.storage.get('token').then((token)=>{
if (token) {
console.log("token true")
return true
} else {
console.log("token false")
return false
}
})
};
像这样修改CanActivate:
async canActivate(): Promise<boolean> {
if(await this.auth.loggedIn()){
return true
} else {
this._router.navigate(['/login'])
return false
};
};