【问题标题】:Is it possible to use parent provider in child directives in angular 2是否可以在角度 2 的子指令中使用父提供程序
【发布时间】: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


    【解决方案1】:

    您在 SimpleDirective.ts 中有错误的 import 语句。改变这个

    import { CurrentTimeService  } from "./currentTimeService"
    

    import { CurrentTimeService  } from "./CurrentTimeService"
    

    Plunker example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 2015-06-10
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多