[英]Redirect to a different component inside @CanActivate in Angular2
我們有什么方法可以從Angular2中的@CanActivate重定向到另一個組件嗎?
截至今天,最新的@ angular / router 3.0.0-rc.1,以下是關於如何通過CanActivate
上的CanActivate
防護來做到這一點的幾個參考:
邏輯的主要要點如下:
// ...
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isLoggedIn) {
// all ok, proceed navigation to routed component
return true;
}
else {
// start a new navigation to redirect to login page
this.router.navigate(['/login']);
// abort current navigation
return false;
}
}
您的護理人員可以很容易地成為一種注射劑,因此可以包含自己的注射劑。 所以我們可以簡單地注入路由器,以便重定向 。 不要忘記在您的應用模塊中將服務添加為提供者。
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
if (!authService.isAuthenticated()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
export const ROUTES: Routes = [
{path: 'login', component: LoginComponent},
{path: 'protected', loadChildren: 'DashboardComponent', canActivate: [AuthGuard]}
];
是的你可以! 這樣做可以防止組件實例化。
首先,創建一個新文件src/app-injector.ts
let appInjectorRef;
export const appInjector:any = (injector = false) => {
if (!injector) {
return appInjectorRef;
}
appInjectorRef = injector;
return appInjectorRef;
};
然后,從bootstrap
獲取引用
// ...
import {appInjector} from './app-injector';
// ...
bootstrap(App, [
ROUTER_PROVIDERS
]).then((appRef) => appInjector(appRef.injector));
最后在你的功能
// ...
import {appInjector} from './app-injector';
// ...
@CanActivate((next, prev) => {
let injector = appInjector();
let router = injector.get(Router);
if (42 != 4 + 2) {
router.navigate(['You', 'Shall', 'Not', 'Pass']);
return false;
}
return true;
})
Etvoilà!
這里討論了https://github.com/angular/angular/issues/4112
你可以在這里找到一個完整的例子http://plnkr.co/edit/siMNH53PCuvUBRLk6suc?p=preview by @brandonroberts
這可能有助於在繼續之前嘗試等待某事的人。
waitForBonusToLoad(): Observable<[boolean, string]> {
const userClassBonusLoaded$ = this.store.select(fromRoot.getUserClasssBonusLoaded);
const userClassSelected$ = this.store.select(fromRoot.getClassAttendancesSelectedId);
return userClassBonusLoaded$.withLatestFrom(userClassSelected$)
.do(([val, val2]) => {
if (val === null && val2 !== null) {
this.store.dispatch(new userClassBonus.LoadAction(val2));
}
})
.filter(([val, val2]) => {
if(val === null && val2 === null) return true;
else return val;
})
.map(val => {
return val;
})
.take(1);
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.waitForBonusToLoad().map(([val, val2]) =>
{
if(val === null && val2 === null){
this.router.navigate(['/portal/user-bio']);
return false;
}
else {
return true;
}
}
)
}
如果您使用observable來確定,則可以利用rxjs
tap
操作符:
@Injectable({
providedIn: SharedModule // or whatever is the equivalent in your app
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.authService.isLoggedIn()
.pipe(tap((isLoggedIn: boolean) => {
if (!isLoggedIn) {
this.router.navigate(['/']);
}
}));
}
}
從Angular 7.1開始,您可以返回UrlTree
而不是boolean
:
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate(): boolean | UrlTree {
return this.authService.isAuthenticated() || this.router.createUrlTree(['/login']);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.