2
如果值爲false,那麼我不會設法將受保護組件HeaderComponent
重定向到LoginComponent
組件,但函數canActivate。Angular 2 RC5 - 使用Observable重定向路線
的HeaderComponent
組件和他們的孩子受到保護,只有訪問URL http://localhost:3000/#/header/index
屏幕變爲空白,我希望它被引導到http://localhost:3000/#/auth
是登錄屏幕
任何人都知道怎麼幫我?
auth.guard.ts
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import {Observable, BehaviorSubject} from 'rxjs/Rx';
import 'rxjs/operator/take';
import {LoginService} from './login/login.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private loginService: LoginService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | boolean {
this.loginService.logado()
.subscribe(
data => {
return data //true
},
error => {
this.loginService.redirectUrl = state.url;
this.router.navigate(['/auth']);
return error //false
}
)
return this.loginService.logado().take(1);
}
}
routes.component.ts
import {Routes, RouterModule} from '@angular/router';
import {LoginComponent} from './login/login.component';
import {HeaderComponent} from './header/header.component';
import {AuthGuard} from './auth.guard';
import {UserComponent} from './user/user.component';
import {IndexComponent} from './index/index.component';
import {UserPasswordComponent} from './user/user.password.component';
export const appRoutes: Routes = [
{path: 'auth', component: LoginComponent},
{path: 'user', component: UserPasswordComponent},
{path: 'header', component: HeaderComponent, canActivate: [AuthGuard],
children: [
{path: 'index', component: IndexComponent},
{path: 'user', component: UserComponent}
]
},
{path: '', redirectTo: 'auth', pathMatch: 'full'},
];
export const routing = RouterModule.forRoot(appRoutes);