Angular2与ES6 - 依赖注入

时间:2016-12-11 17:51:22

标签: angular dependency-injection ecmascript-6

app.module.js

AppModule.annotations = [
new NgModule({
    declarations: [
        SomeComponent
    ],
    providers: [
        {provide: SOME_CONSTANT, useValue: 'whatever'}
    ]
})];

如何将 SOME_CONSTANT 注入 SomeComponent (some.component.js)?

SomeComponent.parameters = [
  [SOME_CONSTANT]
];

不起作用。显而易见的是,解释器将如何知道SOME_CONSTANT是什么。

1 个答案:

答案 0 :(得分:0)

我认为为这种情况使用服务并将服务注入SomeComponent的构造函数可能是有意义的:

应用模块

AppModule.annotations = [
new NgModule({
  declarations: [SomeComponent],
  providers: [ConstantService]
})];

常量服务

import { Injectable } from '@angular/core';

@Injectable()
export class ConstantService {
  SOME_CONSTANT = 'whatever';
}

某个组件

import { Component } from '@angular/core';
import { ConstantService } from './constant.service';

@Component({...})
export class SomeComponent {
  constructor SomeComponent(constants: ConstantService) {
    let someConstant = constants.SOME_CONSTANT;
  }
}