Service class is not injected in Angular2

2019-07-10 03:02发布

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.

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]
})

The template of that component contains: <secure-outlet signin="Login" unauthorized="AccessDenied"></secure-outlet>

Where the secure-outlet implementation is as follows:

@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);
    }
...

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.

What am I missing?

Thanks,

1条回答
▲ chillily
2楼-- · 2019-07-10 03:55

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

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) {
查看更多
登录 后发表回答