在 Angular2 中重定向到@CanActivate 中的不同组件 [英] Redirect to a different component inside @CanActivate in Angular2
本文介绍了在 Angular2 中重定向到@CanActivate 中的不同组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么办法可以从 Angular2 中的 @CanActivate 重定向到不同的组件吗?
Is there any way we can redirect to a different component from @CanActivate in Angular2 ?
推荐答案
是的,你可以!这样做可以防止您的组件无故实例化.
Yes, you can! Doing this will prevent your component from instantiating for nothing.
首先新建一个文件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;
})
等等!
这里讨论过https://github.com/angular/angular/issues/4112
您可以在此处找到完整示例 http://plnkr.co/edit/siMNH53PCuvUBRLk6suc?p=预览 @brandonroberts
You can find a complete example here http://plnkr.co/edit/siMNH53PCuvUBRLk6suc?p=preview by @brandonroberts
这篇关于在 Angular2 中重定向到@CanActivate 中的不同组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文