【问题标题】:Angular2 DI accessing static propertiesAngular2 DI 访问静态属性
【发布时间】:2016-09-02 13:39:34
【问题描述】:

我有以下 TS 课

从“@angular/core”导入 { Injectable };

@Injectable()
export class Config {

    /**
     * [AuthServiceUrl description]
     * @type {string}
     */
    static AuthServiceUrl: string = 'http://localhost:3000';
}

注意 AuthServiceUrl 是静态的。如果我有这样的东西,如何在 Angular2s DI 框架中访问这个属性

constructor(private config: Config)

我如何访问它。另外,如果我想制作 Config 类 Singleton,我该如何在 Angular2 中做到这一点?

【问题讨论】:

  • 静态属性在某种程度上违背了 DI 的目的。为什么它必须是静态的?

标签: angular dependency-injection static


【解决方案1】:

https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#opaque-token 所述,声明配置变量并在可以声明 opaque-token 的任何地方使用它。

声明config接口和接口提供者如下:

=> config.ts

export interface Config {
  apiEndpoint: string;
}

export const CONFIG: Config = {
  apiEndpoint  : 'http://api.url.com'
};

=> config.provider.ts

import { OpaqueToken } from '@angular/core';
export let APP_CONFIG = new OpaqueToken('app.config');

在一些共享模块中使用它,如下所示:

=> shared.module.ts

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

import { CONFIG } from './config';
import { APP_CONFIG } from './config.provider';

@NgModule({
  providers : [
    {
      provide : APP_CONFIG,
      useValue: CONFIG
    }
  ]
})
export class SharedModule {}

【讨论】:

    猜你喜欢
    • 2018-04-18
    • 2013-02-13
    • 2013-04-27
    • 2015-05-20
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多