Angular2 - 将单件服务注入指令

时间:2016-06-11 21:44:18

标签: dependency-injection angular

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

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

1 个答案:

答案 0 :(得分:1)

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

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

不等于

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

是的,这是愚蠢的,但它使依赖注入无法进行。