注入需要构造函数参数的服务 [英] Inject a service requiring constructor parameter

查看:64
本文介绍了注入需要构造函数参数的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项服务,需要一些值才能启动:

I have a service that requires some value to be initiated:

@Injectable()
export class MyService {
  private myVals: any;

  constructor(init : any) {
    this.myVals = init;
  }
}

和消费者:

@Component(...)
export class MyComponent {
  private svc: MyService;
  constructor(private svc : MyService) {
  }
}

因此,有一种方法可以在依赖项注入期间"注入所需的参数并将其传递给 MyService constructor ?

So is there a way to inject and pass the required parameter to MyService's constructor "during" dependency injection??

类似的东西:

constructor(private svc({ // init vales }) : MyService) {}

我知道我可以传递变量,但是有兴趣寻找是否可以通过API进行此操作.

I know I can pass by variable, but interested to find if there's a way to do this from the API.

推荐答案

Angular团队在

There is an official way that Angular team recommends in here. It basically allows you to inject statically typed configuration classes.

我已经成功实现了,这里是所有相关代码:

I have successfully implemented it and here is all the relevant code:

1) app.config.ts

import { OpaqueToken } from "@angular/core";

export let APP_CONFIG = new OpaqueToken("app.config");

export interface IAppConfig {
    apiEndpoint: string;
}

export const AppConfig: IAppConfig = {    
    apiEndpoint: "http://localhost:15422/api/"    
};

2) app.module.ts

import { APP_CONFIG, AppConfig } from './app.config';

@NgModule({
    providers: [
        { provide: APP_CONFIG, useValue: AppConfig }
    ]
})

3) your.service.ts

import { APP_CONFIG, IAppConfig } from './app.config';

@Injectable()
export class YourService {

    constructor(@Inject(APP_CONFIG) private config: IAppConfig) {
             // You can use config.apiEndpoint now
    }   
}

现在,您可以将配置注入到任何地方,而无需使用字符串名称,也无需使用接口进行静态检查.

Now you can inject the config everywhere without using the string names and with the use of your interface for static checks.

您当然可以进一步分离接口和常量,以便能够在生产和开发中提供不同的值,例如

You can of course separate the Interface and the constant further to be able to supply different values in production and development e.g.

这篇关于注入需要构造函数参数的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆