是否可以在 angular 2 中的子指令中使用父提供者
Is it possible to use parent provider in child directives in angular 2
我正在尝试将服务用作指令而不是组件中的一般用途的提供者。但它抱怨说它没有得到子指令中的服务。我希望在指令中使用该服务:
// 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
提前致谢
您在 SimpleDirective.ts 中的 import
语句有误。改变这个
import { CurrentTimeService } from "./currentTimeService"
到
import { CurrentTimeService } from "./CurrentTimeService"
我正在尝试将服务用作指令而不是组件中的一般用途的提供者。但它抱怨说它没有得到子指令中的服务。我希望在指令中使用该服务:
// 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
提前致谢
您在 SimpleDirective.ts 中的 import
语句有误。改变这个
import { CurrentTimeService } from "./currentTimeService"
到
import { CurrentTimeService } from "./CurrentTimeService"