繁体   English   中英

带有ES6的Angular2-依赖注入

[英]Angular2 with ES6 - dependency injection

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是什么。

我认为在这种情况下使用服务并将服务注入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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM