Vin*_*onz 31 angular2-routing angular
我们有什么方法可以从Angular2中的@CanActivate重定向到另一个组件吗?
sup*_*jos 56
截至今天,最新的@ angular/router 3.0.0-rc.1,以下是关于如何通过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;
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*aul 13
Angular 2.0最终解决方案:
您的护理人员可以很容易地成为一种注射剂,因此可以包含自己的注射剂.所以我们可以简单地注入路由器,以便重定向.不要忘记在您的应用模块中将服务添加为提供者.
@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]}
];
Run Code Online (Sandbox Code Playgroud)
Dru*_*tan 12
是的你可以!这样做可以防止组件实例化.
首先,制作一个新文件 src/app-injector.ts
let appInjectorRef;
export const appInjector:any = (injector = false) => {
if (!injector) {
return appInjectorRef;
}
appInjectorRef = injector;
return appInjectorRef;
};
Run Code Online (Sandbox Code Playgroud)
然后,从中获取参考 bootstrap
// ...
import {appInjector} from './app-injector';
// ...
bootstrap(App, [
ROUTER_PROVIDERS
]).then((appRef) => appInjector(appRef.injector));
Run Code Online (Sandbox Code Playgroud)
最后在你的功能
// ...
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;
})
Run Code Online (Sandbox Code Playgroud)
Etvoilà!
这里讨论了https://github.com/angular/angular/issues/4112
你可以在这里找到一个完整的例子http://plnkr.co/edit/siMNH53PCuvUBRLk6suc?p=preview by @brandonroberts
小智 8
从 Angular 7.1 开始,您可以使用 returnUrlTree而不是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']);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30944 次 |
| 最近记录: |