2016-06-28 43 views
0

我試圖使用服務作爲提供程序在指令中使用而不是組件。但它抱怨說它沒有得到兒童指令中的服務。我希望使用該服務的指令:是否有可能使用父提供程序在角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

在此先感謝

回答

2

你必須在SimpleDirective錯誤import聲明.TS。改變這種

import { CurrentTimeService } from "./currentTimeService" 

import { CurrentTimeService } from "./CurrentTimeService" 

Plunker example

+0

非常感謝你!!!!!! –

相關問題