服务类未注入 Angular2 [英] Service class is not injected in Angular2

查看:34
本文介绍了服务类未注入 Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我已经一切正常了.今天,在我重新启动环境后,我尝试注入的服务之一现在总是 null.

I already had everything working yesterday. And today, after I restarted the environment, one of the services that I am trying to inject, is now always null.

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

Here is my top level component (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" authorized="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 定义提供者,在主组件中,甚至在引导程序中,没有任何作用.

In the constructor, as well as anywhere else in the directive, authService is always null. I tried, defining providers with AuthenticationService inside the directive, in the main component, even in the bootstrap, nothing works.

我错过了什么?

谢谢,

推荐答案

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

Don't add providers: [ROUTER_PROVIDERS] to components, only to bootstrap()

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

Try providing the same parameters as the original RouterOutlet class and add your own dependencies behind them. Not sure if this helps though but I think it was mentioned not too long ago that there is a weird issue:

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

这篇关于服务类未注入 Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆