【问题标题】:Angular2 with ES6 - dependency injection带有 ES6 的 Angular2 - 依赖注入
【发布时间】:2017-04-26 15:07:31
【问题描述】:

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

【问题讨论】:

    标签: angular dependency-injection ecmascript-6


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      相关资源
      最近更新 更多