将参数传递给Angular中@Injectable的构造函数?

问题描述 投票:0回答:1

假设我们有这样的@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个回答
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'},
...
© www.soinside.com 2019 - 2024. All rights reserved.