Angular 2 : Inject a dependency into @CanActivate?

标签 angular angular2-routing

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

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

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

最佳答案

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

他引用了这个 Plunk:http://plnkr.co/edit/SF8gsYN1SvmUbkosHjqQ?p=preview

它的主要思想是一个单例注入(inject)器,他在应用程序初始化时保存它。这提供了对您已经配置的根依赖项的访问,并进一步允许您的服务像它们可能预期的那样作为单例共享:

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);
});

关于 Angular 2 : Inject a dependency into @CanActivate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34711962/

相关文章:

angular - 我如何制作 MatDialog 可拖动/Angular Material

angular - 如何强制下载 Angular PWA

angularjs - 如何使用 oauth2 登录重定向到 Angular 路由器链接?

angular - 错误 : Cannot find the outlet myteam_outlet to load 'MemberListingComponent'

路由前的 Angular 超时

javascript - 你能在 Angular 2 中有一个独立的指令吗

angular - 允许在 cdkDropList 中水平定位

angular - 我如何在 angular 6 中使用 mdi 图标

angular - 如何在 angular2 中将事件从 app.component 广播到路由器导出

javascript - Angular 5 页面刷新总是登陆首页而不是在同一页面