简体   繁体   中英

Angular2 with ES6 - dependency injection

app.module.js

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

How can I inject SOME_CONSTANT to SomeComponent (some.component.js)?

SomeComponent.parameters = [
  [SOME_CONSTANT]
];

Doesn't work. What is obvious because how interpreter would know what SOME_CONSTANT is.

I think it probably makes sense to use a service for this scenario and inject the service into SomeComponent's constructor:

App Module

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

Constant Service

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

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

Some Component

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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