@RouteConfig([
{
path: '/login',
name: 'Login',
component: LoginComponent
},
{
path: '/search',
name: 'Search',
component: SearchComponent,
needAuth: true
},
{
path: '/result/:searchString',
name: 'Result',
component: ResultComponent,
needAuth: true
},
{path: '/**', redirectTo: ['Login']}
])
我有一个配置,如何检测当前路由对象;
{
path: '/result/:searchString',
name: 'Result',
component: ResultComponent,
needAuth: true
}
用于未登录用户时的路由限制。
我想这样做;
export class AppComponent {
constructor(private _authService:AuthenticationService) {
if (this._authService.getUser() != null && CURRENT ROUTE OBJECT's needAuth PROPERTY is TRUE) {
this._router.navigate(['Search'])
} else {
this._router.navigate(['Login'])
}
}
}
欢迎各种帮助。
************** UPDATE ********************
我找到了这个解决方案
this._router.subscribe((url) => {
this._router.recognize(url).then((instruction) => {
if(this._authService.getUser() == null && instruction.component.routeData.data.needAuth) {
this._router.navigate(['Login'])
}
if(this._authService.getUser() !=null && !instruction.component.routeData.data.needAuth) {
this._router.navigate(['Search'])
}
});
});
答案 0 :(得分:0)
而不是
needAuth: true
<{1>}使用中的
RouteConfig
然后注入
data: {needAuth: true}
答案 1 :(得分:0)
我认为您可以扩展RouterOutlet
类以全局方式拦截路由激活:
import {Directive} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';
@Directive({
selector: 'router-outlet'
})
export class MyOwnRouterOutlet extends RouterOutlet {
(...)
activate(oldInstruction: ComponentInstruction) {
var url = this.parentRouter.lastNavigationAttempt;
console.log('attemping to nav');
if (oldInstruction.routeData.needAuth && !this.authService.loggedIn){
var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
return super.activate(newInstruction);
} else {
return super.activate(oldInstruction);
}
}
}
您需要以这种方式配置路线:
{
path: '/result/:searchString',
name: 'Result',
component: ResultComponent,
data: {
needAuth: true
}
}
有关详细信息,请参阅以下链接: