【问题标题】:Angular2 - inject singleton Service into DirectiveAngular2 - 将单例服务注入指令
【发布时间】:2016-06-11 21:44:17
【问题描述】:

我在将单例服务注入指令时遇到问题。 我有服务:

@Injectable()
export class AuthService{ ... }

我把它放到引导程序中。

bootstrap(AppComponent, [AuthService, ...]);

我制定了指令,保护我的组件:

@Directive({
  selector: '[protected]'
})
export class ProtectedDirective {
   constructor(private authService:AuthService) { ... }
}

...并添加到组件之一

@Component({
  selector: 'dashboard',
  directives: [ProtectedDirective],
  template: '<div protected></div',
})
export class DashboardCmp { }

在控制台中我看到一个错误:

ORIGINAL EXCEPTION: No provider for AuthService!

如果我将提供程序添加到 DashboardCmp,一切正常,但它不是单例服务。我在其他组件中设置了它的属性,当我在指令中时我看不到它们。

【问题讨论】:

    标签: dependency-injection angular


    【解决方案1】:

    我解决了我的问题。一切都很好,但是

    import {AuthService} from '../services/auth.service'; (in protected.directive.ts)
    

    不等于

    import {AuthService} from '../Services/auth.service'; ( in main.ts)
    

    是的,这很愚蠢,但它使依赖注入变得不可能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 2017-06-24
      • 2014-02-08
      • 2016-02-08
      • 2016-02-12
      • 2016-05-09
      • 2017-06-27
      相关资源
      最近更新 更多