Angular2 - 将单例服务注入指令



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

@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,一切正常,但它不是单例服务。我在其他组件中设置了它的属性,当我在指令中时看不到它们。

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

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

不等于

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

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

最新更新