这可能是一个基本问题,但在Angular2中有没有办法进行条件路由?或者,有人会在路由器之外这样做吗?
我知道ui-router有能力做到这一点,但我没有在Angular2s路由器中看到类似的东西
ber*_*ing 40
如前所述,Angular Route Guards是实现条件路由的好方法.由于Angular Tutorial在这个主题上有点冗长,这里有一个简短的总结如何将它们与一个例子一起使用.
1.有几种类型的警卫.如果您需要某些逻辑if (loggedIn) {go to "/dashboard"} else { go to "/login"}
,那么您正在寻找的是CanActivate
-Guard.CanActivate可以读作"如果满足所有条件Y,则可以激活新路径X".您还可以定义重定向等副作用.如果这不符合您的逻辑,请查看Angular Tutorial页面以查看其他防护类型.
2.创建一个auth-guard.service.ts
.
3.auth-guard.service.ts
使用以下代码填充:
import { Injectable } from '@angular/core';
import {CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(
private router: Router
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const isLoggedIn = false; // ... your login logic here
if (isLoggedIn) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
4.在路由模块中注册auth-guard.service.ts.此外,将键值对添加canActivate:[AuthGuardService]
到要保护的所有路由.它应该看起来像这样:
const appRoutes: Routes = [
{ path: '', component: LandingComponent},
{ path: 'login', component: LoginComponent},
{ path: 'signup', component: SignUpComponent},
{ path: 'home', component: HomeComponent, canActivate: [AuthGuardService]},
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuardService]},
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
],
providers: [
AuthGuardService
]
})
export class AppRoutingModule { }
Run Code Online (Sandbox Code Playgroud)
这应该让你开始.
这是一个简约的演示:https://stackblitz.com/edit/angular-conditional-routing
更新
在新的路由器中可以使用防护装置 https://angular.io/guide/router#milestone-5-route-guards
原始的(对于久违的路由器)
实现CanActivate
生命周期钩子,如此处所示生命周期钩子在Angular2路由器中,如果要阻止导航,则返回false.另见https://angular.io/docs/ts/latest/api/router/CanActivate-var.html
如果您需要渲染特定组件而不是重定向到它,您可以执行以下操作:
const appRoutes: Routes = [
{
path: '' ,
component: (() => {
return SessionService.isAnonymous() ? LoginComponent : DashboardComponent;
})()
}
]
Run Code Online (Sandbox Code Playgroud)
我将此示例用于登录页面,其中之前未登录的用户将看到登录页面或仪表板仪表板.
更新 此代码将在开发环境中工作,但它不会构建,您将收到此错误:
在"AppRoutingModule"的模板编译过程中出现错误错误'ɵ0'中的装饰器不支持函数表达式''0'包含src/app/app.routing-module.ts(14,25)中的错误考虑将函数表达式更改为导出的功能.
为了解决这个问题,我创建了一个单独的模块,如下所示
import {LandingPageComponent} from '../landing-page/landing-page.component';
import {DashboardComponent} from "../dashboard/dashboard.component";
import {SessionService} from "../core/services/session.service";
const exportedComponent = SessionService.isAnonymous() ? LandingPageComponent : DashboardComponent;
export default exportedComponent;
Run Code Online (Sandbox Code Playgroud)
然后你只需要导入那个"工厂"提供的模块
import LandingPageComponent from './factories/landing-factory.component';
const appRoutes: Routes = [
{
path: '' ,
component: LandingPageComponent
},
]
Run Code Online (Sandbox Code Playgroud)