微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

重定向到Angular2中的@CanActivate内的其他组件

有没有什么办法可以重定向到另一个组件从@CanActivate在Angular2?
是的你可以!这样做会阻止您的组件实例化。

首先,创建一个文件src / app-injector.ts

let appInjectorRef;

export const appInjector:any = (injector = false) => {
    if (!injector) {
        return appInjectorRef;
    }

    appInjectorRef = injector;

    return appInjectorRef;
};

然后,从引导中获取引用

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

Etvoilà!

这里已经讨论了https://github.com/angular/angular/issues/4112

你可以在这里找到一个完整的例子http://plnkr.co/edit/siMNH53PCuvUBRLk6suc?p=preview by @brandonroberts

原文地址:https://www.jb51.cc/angularjs/144086.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐