在Angular的路由文件中使用服务

时间:2018-11-02 08:53:13

标签: angular

我需要根据服务方法返回的条件动态定义解析器。这是路由文件中的代码:

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {MyComponent} from './components/myComponent/myComponent.component';
import {TestResolver} from './../_resolvers/test.resolver';
import {OtherResolver} from '../_resolvers/other.resolver';
import {PrivilegesCheckerService} from './../auth/_services/privileges_checker.service';

const routes: Routes = [
  {
      path: '',
      component: MyComponent,
      resolve: {
          item: OtherResolver
      }
    }
];

//  Get the test data only if the user has the 'TEST_PRIVILEGE' privilege --> This doesn't work
if(this.privilegesCheckerService.checkPrivileges(['TEST_PRIVILEGE'])) {
    routes[0].resolve.test = TestResolver;
}

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AuthRoutingModule {
}

当我通常在组件内部使用服务时,我导入服务,将其声明到组件的构造函数中,并像this.myService.myMethod()一样使用它,但是在这种情况下,它不起作用,因为thisexport class AuthRoutingModule { }声明之外无效。 我收到的错误与服务定义文件中不存在的currentUser(存储在localStorage中)有关(我不确定这是否相关)。请指教。谢谢!

0 个答案:

没有答案