【问题标题】:Passing arguments to the constructor of an @Injectable in Angular?将参数传递给Angular中@Injectable的构造函数?
【发布时间】:2018-03-01 06:21:47
【问题描述】:

假设我们有一个像这样的@Injectable 类:

interface IServiceConfig {
    boo: string;
    foo: string;
}

@Injectable()
class Service {
    boo: string = "boo";
    foo: string = "foo";

    constructor(IServiceConfig isc) {
       Object.assign(this, isc);
    }
}

是否可以将IServiceConfig 实例传递给Service 的构造函数,同时仍允许Angular 创建和注入Service 实例?

在 Angular 创建服务实例之前,是否有不同的方式来配置服务?

【问题讨论】:

    标签: javascript angular dependency-injection


    【解决方案1】:

    这是未经测试的,但你应该可以这样做:

    import { Injectable, Inject, Optional } from '@angular/core';
    
    interface IServiceConfig {
        boo: string;
        foo: string;
    }
    
    @Injectable()
    class Service {
        boo: string = "boo";
        foo: string = "foo";
    
        constructor(@Inject('isc') @Optional() public isc?: IServiceConfig ) {
           Object.assign(this, isc);
        }
    }
    

    在您的提供者中(例如在 app.module 中):

    providers: [
        {provide: 'isc', useValue: {boo: 'hoo', foo: 'bar'},
    ...
    

    【讨论】:

    • 简洁优雅!希望它有效!无论哪种方式,我都非常喜欢它,我会投票并接受!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2015-10-11
    相关资源
    最近更新 更多