角2:注入的依赖到@CanActivate? [英] Angular 2: Inject a dependency into @CanActivate?
问题描述
在角2,您可以为组件在那里你可以决定是否组件时,应激活或不指定 @CanActivate
注释。它不是一个接口的原因是因为之前的组件甚至实例回调被调用。问题是,我不能想出一个办法来获得注入到回调的依赖。我需要我的服务,告诉我我是否登录或没有(和谁)来确定是否路由到特定组件允许与否。
In Angular 2, you can specify a @CanActivate
annotation for a component where you can determine if the component should be activated or not. The reason it's not an interface is because the callback is called before the component is even instantiated. The problem is, I can't figure out a way to get dependencies injected into that callback. And I need my service that tells me whether I'm logged in or not (and as whom) to determine whether routing to a particular component is allowed or not.
我怎么能注入的依赖变成@CanActivate回调?我使用ES5,这不工作:
How can I inject a dependency into a @CanActivate callback? I'm using ES5, and this doesn't work:
app.ListsComponent = ng.router.CanActivate([
app.SessionService,
function(session, instruction) {
console.log(session);
return true;
}
])(app.ListsComponent);
编辑:或者,我可以在组件上使用 routerOnActivate
生命周期事件,并使用 this.router.navigate
向用户发送的路程,如果他们不应该在那里。缺点有,它打破浏览器历史记录:如果我每天都在你一个特定的URL时到达您重定向异步,你无法在浏览器中使用后退按钮非常有用。有没有办法让 router.navigate
使用 history.replaceState
而不是 history.pushState
对于这种情况?
Alternatively, I can use the routerOnActivate
lifecycle event on the component, and use this.router.navigate
to send the user away if they're not supposed to be there. The downside there is that it breaks browser history: If I redirect you asynchronously every time you arrive at a particular URL, you can't use the Back button in your browser very usefully. Is there a way to have router.navigate
use history.replaceState
instead of history.pushState
for this kind of situation?
推荐答案
大多数解决方案,这里将美元,装载子依赖性p $ psent问题从层次结构别处,因为他们创造一个新的注射器。此外,这将导致在被实例化的其他(非共享)服务。我建议按照 https://github.com/angular/angular/issues/布兰登提供的模式4112
Most solutions here will present problems with loading sub-dependencies from elsewhere in the hierarchy, because they create a new injector. Also, this results in additional (non-shared) services being instanced. I recommend following the pattern provided by Brandon in https://github.com/angular/angular/issues/4112
他引用此普拉克: http://plnkr.co/edit/SF8gsYN1SvmUbkosHjqQ? p = preVIEW
它的主要思想是一个单独的喷油器,当应用程序初始化,他的扑救。这提供了访问您已配置了根的依赖关系,并且还允许您服务,为独立的共享,因为他们很可能打算:
Its main idea is a singleton injector, which he saves when the app initializes. This provides access to the root dependencies you already have configured, and further allows your services to be shared as a singleton as they were probably intended:
import {Injector} from 'angular2/angular2';
let appInjectorRef: Injector;
export const appInjector = (injector?: Injector):Injector => {
if (injector) {
appInjectorRef = injector;
}
return appInjectorRef;
};
bootstrap([ServiceYouNeed]).then((appRef) => {
// store a reference to the injector
appInjector(appRef.injector);
});
这篇关于角2:注入的依赖到@CanActivate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!