【发布时间】:2017-06-11 18:15:23
【问题描述】:
服务:
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { Router } from '@angular/router';
import { AngularFireAuth } from 'angularfire2/auth';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, public af: AngularFireAuth) { }
canActivate() {
this.af.authState.subscribe(res => {
if (res && res.uid) {
this.router.navigate(['/dashboard']);
} else {
// Prevent user from accessing any route other than /login or /register.
}
});
return true;
}
}
路由器模块:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth-guard.service';
import { LoginComponent } from 'app/login/login.component';
import { RegisterComponent } from 'app/register/register.component';
import { DashboardComponent } from 'app/dashboard/dashboard.component';
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent, canActivate:[AuthGuard] },
{ path: 'register', component: RegisterComponent, canActivate:[AuthGuard] },
{ path: 'dashboard', component: DashboardComponent, canActivate:[AuthGuard] },
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: '**', redirectTo: '/login', pathMatch: 'full' }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
canActivate 函数的作用是重定向用户是否登录。我在路由器模块中的路由上附加了警卫,但我无法确定下一步的正确逻辑:
如果用户没有登录,他们应该不能访问除 /login 或 /register 之外的任何路由。当然,我可以在 else 语句中添加 this.router.navigate(['/login']),但这会使 /register 无法访问。
感谢您的任何见解。
【问题讨论】:
标签: angular routes angular2-routing