在UI路由器配置功能中使用事件发射器(Angular 2/4)

时间:2018-01-03 00:34:33

标签: javascript angular angular-ui-router

我已经能够将我的自定义TokenService导入UI路由器配置功能(如下所示)而不会出现问题:

import { UIRouter, Category } from '@uirouter/core';

import { TokenService } from './_services/token.service';
import { NOAUTH_STATES } from './app.states';

export function routerConfigFn(router: UIRouter) {
  const transitionService = router.transitionService;

  router.trace.enable(Category.TRANSITION);

  transitionService.onStart({}, transition => {
    let token = sessionStorage.getItem('access_token');
    let unguarded = [];

    NOAUTH_STATES.forEach(state => unguarded.push(state.name));

    // EVENT EMITTER CODE (BELOW) GOES HERE

    if (unguarded.indexOf(transition.to().name) === -1) {
      let token = sessionStorage.getItem('access_token');

      if (!!token) {
        transition.injector().get(TokenService).tokenInfoGet(token).subscribe( // <--- HERE
          (data: any) => {
            return;
          },
          (error: any) => {
            transition.injector().get(TokenService).validate(retryGuardedRoute); // <-- AND HERE
          });
      } else {
        transition.injector().get(TokenService).validate(retryGuardedRoute); // <-- AND HERE
      }
    }
  });
}

// retryGuardedRoute is another method not shown here, but it uses the same
// transition.injector().get(TokenService) call to the validate method as
// shown in the 'error', and 'else' sections above

但是,一旦我尝试使用来自同一服务的事件发射器而不是上面显示的方法调用,我就会收到“No Provider”错误消息。 (下面的代码,插入上面的配置代码中的'EVENT EMITTER GOES HERE'评论):

transition.injector().get(TokenService).authorizeUpdated.subscribe(
  (data: any) => {
    console.log('waited...');
    if (data === true) {
      return;
    } else {
      return router.stateService.target('login');
    }
  },
  (error: any) => {
    console.log('waiting, now redirecting');
    return router.stateService.target('login');
  }
);

我的自定义服务或路由器配置中是否需要额外的设置才能从配置功能中成功订阅事件发射器,或者这是不可能的?

0 个答案:

没有答案