我正在尝试将服务用作指令的一般用途,而不是组件。但它抱怨它没有在儿童指令中获得服务。我希望在指令中使用该服务:
// 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() { }
*/
}
你可以检查一下整个程序:https://plnkr.co/edit/s0zUkI?p=preview
提前致谢
答案 0 :(得分:2)
SimpleDirective.ts中有一个错误的#include <iostream>
struct Foo : std::ofstream {};
template <typename T>
Foo& operator<<(Foo& strm, const T& var)
{
std::cout << "X" << std::endl;
return strm;
};
int main() {
Foo oac;
oac << std::endl;
}
语句。改变这个
import
到
import { CurrentTimeService } from "./currentTimeService"