Angular 2:将依赖项注入@CanActivate?

Ben*_*lts 10 angular2-routing angular

在Angular 2中,您可以@CanActivate为组件指定注释,您可以在其中确定是否应激活组件.它不是接口的原因是因为在组件被实例化之前调用了回调.问题是,我无法找到一种方法来将依赖注入到该回调中.我需要我的服务,告诉我我是否登录(以及作为谁)以确定是否允许路由到特定组件.

如何将依赖项注入@CanActivate回调?我正在使用ES5,但这不起作用:

app.ListsComponent = ng.router.CanActivate([
    app.SessionService,
    function(session, instruction) {
        console.log(session);
        return true;
    }
])(app.ListsComponent);
Run Code Online (Sandbox Code Playgroud)

编辑:或者,我可以routerOnActivate在组件上使用生命周期事件,并使用它this.router.navigate来发送用户,如果他们不应该在那里.缺点是它会破坏浏览器历史记录:如果每次到达特定URL时我都会异步重定向您,则无法在浏览器中非常有用地使用"后退"按钮.有没有办法router.navigate使用history.replaceState而不是history.pushState这种情况?

sha*_*non 7

此处的大多数解决方案都会出现从层次结构中的其他位置加载子依赖关系的问题,因为它们会创建新的注入器.此外,这会导致实例化其他(非共享)服务.我建议遵循Brandon在https://github.com/angular/angular/issues/4112中提供的模式

他引用了这篇文章:http://plnkr.co/edit/SF8gsYN1SvmUbkosHjqQ?p = preview

它的主要思想是单例注入器,当应用程序初始化时,它会保存.这提供了对您已配置的根依赖项的访问,并进一步允许您的服务作为单例共享,因为它们可能是:

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);
});
Run Code Online (Sandbox Code Playgroud)


Lan*_*ley 1

我不知道这是否是最好的方法,但这些人通过扩展和使用自己的方法<router-outlet>并覆盖该CanActivate方法来做到这一点:

https://auth0.com/blog/2015/05/14/creating-your-first-real-world-angular-2-app-from-authentication-to-calling-an-api-and-everything-in-之间/

你也可以用routerOnActivate它来代替。

https://angular.io/docs/js/latest/api/router/OnActivate-interface.html 我希望这有帮助。