【发布时间】:2016-06-28 11:30:17
【问题描述】:
我正在尝试将服务作为提供者用于指令中的一般用途,而不是组件。但它抱怨它没有在子指令中获得服务。我希望在指令中使用该服务:
// CurrentTimeService.ts
import { Injectable } from '@angular/core'
@Injectable()
export class CurrentTimeService {
dt: number;
constructor() {
this.dt = new Date().getTime();
}
}
app.ts
//our root app component
import {Component} from '@angular/core'
import {CurrentTimeService} from "./CurrentTimeService"
import {SimpleDirective} from "./SimpleDirective"
@Component({
selector: 'my-app',
providers: [CurrentTimeService],
template: `
<div>
<h2 mySimpleDirective>Hello {{name}}</h2>
</div>
`,
directives: [SimpleDirective]
})
export class App {
constructor() {
this.name = 'Angular2 (Release Candidate!)'
}
}
SimpleDirective.ts
import {Directive} from '@angular/core';
import { CurrentTimeService } from "./currentTimeService"
@Directive({
selector: '[mySimpleDirective]'
})
export class SimpleDirective {
constructor(private currentTimeService: CurrentTimeService) {
}
/*
uncomment this command, it is working because it doesn't demand the service
constructor() { }
*/
}
您可以查看 plunker 以查看完整的程序:https://plnkr.co/edit/s0zUkI?p=preview
提前致谢
【问题讨论】:
标签: typescript angular angular2-directives