【问题标题】:Service class is not injected in Angular2服务类未注入 Angular2
【发布时间】:2016-04-06 08:11:57
【问题描述】:

我昨天已经完成了所有工作。而今天,在我重新启动环境后,我尝试注入的服务之一现在始终是null

这是我的顶级组件(app.component.ts):

@Component({
  selector: 'priz-app',
  moduleId: module.id,
  templateUrl: './app.component.html',
  directives: [ROUTER_DIRECTIVES, SecureRouterOutlet],
  providers: [ROUTER_PROVIDERS, AuthenticationService]
})

该组件的模板包含: <secure-outlet signin="Login" unauthorized="AccessDenied"></secure-outlet>

其中secure-outlet的实现如下:

@Directive({
    selector: 'secure-outlet'
})
export class SecureRouterOutlet extends RouterOutlet {
    @Input()
    signin: string;

    @Input()
    unauthorized:string;

    @Input()
    nameAttr: string;

    constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader,
                private parentRouter: Router,
                private authService: AuthenticationService,
                public injector: Injector) {
        super(_elementRef, _loader, parentRouter, null);
    }
...

在构造函数中,以及指令中的其他任何地方,authService 始终是null。我尝试在指令内、主要组件中、甚至在引导程序中使用 AuthenticationService 定义提供程序,但没有任何效果。

我错过了什么?

谢谢,

【问题讨论】:

  • 首先从 providers 数组中移除 ROUTER_PROVIDERS 并在引导函数中使用它。

标签: dependency-injection angular angular-directive


【解决方案1】:

不要将providers: [ROUTER_PROVIDERS]添加到组件中,添加到bootstrap()

尝试提供与原始RouterOutlet 类相同的参数,并在它们后面添加您自己的依赖项。 不确定这是否有帮助,但我认为不久前有人提到有一个奇怪的问题:

constructor(
    _elementRef: ElementRef, 
    _loader: DynamicComponentLoader,
    private parentRouter: Router,
    @Attribute('name') nameAttr: string, // <= added
    private authService: AuthenticationService,
    public injector: Injector) {

【讨论】:

  • 好的,这确实有效,甚至有点道理。但是,现在我收到此错误:/Users/ShurikAg/Dev/angular2/ng2/src/shared/directives/securerouter.directive.ts line 47 col 17 In the constructor of class "SecureRouterOutlet", the parameter "nameAttr" uses the @Attribute decorator, which is considered as a bad practice. Please, consider construction of type "@Input() nameAttr: string".
  • 嗯,对我来说这没有意义。恕我直言,构造函数中依赖项的数量、种类和顺序无关紧要。似乎路由器插座的实例化方式有些可疑。 github.com/angular/angular/issues/7569 是我在讨论中看到的。
  • 我应该怎么处理这个错误?我的意思是,它仍然有效,但 @Attribute 装饰器是一种不好的做法是有原因的。
  • 啊,没有阅读完整的评论。这是一个非常奇怪的信息。不知道是什么产生的。我也看不出它有什么不好。如果您只对静态值感兴趣并且不想收到关于以后更新的通知@Attribute 就可以了。 @Input() 在实际用例中会非常麻烦。我在 Angular2 GitHub 存储库中找不到此错误消息。
猜你喜欢
  • 1970-01-01
  • 2017-06-24
  • 2017-04-09
  • 1970-01-01
  • 2017-08-11
  • 2016-05-09
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多