在Angular参数中注入依赖关系的正确方法是什么

时间:2019-12-06 05:58:42

标签: angular typescript dependency-injection

我去年才开始学习角度,而偶然发现了角度依赖注入。情况是我需要注入需要实例化某些参数的依赖项。目前,我正在这样做:

some-dependency.service.ts

import { Injectable } from '@angular/core';
import { ConfigService } from 'app/services/config.service';
import { Client } from 'some-dependency';

@Injectable({
    providedIn: 'root',
    useFactory: (config:ConfigService) => new Client({
        host:config.clientURL, maxRetries: config.maxRetry
    }),
    deps: [ConfigService]
})

export class SomeDependencyService extends Client {

}

another-service.service.ts

import { Injectable } from '@angular/core';
import { SomeDependencyService } from 'app/services/some-dependency.service';

@Injectable({
  providedIn: 'root'
})

export class SomeService {

    constructor( private deps: SomeDependencyService ) {}

    getSomething() {
        return this.deps.get('something');
    }
} 

代码工作正常,我可以毫无问题地在Client中实例化another-service.ts实例,而且我可以轻松地对其进行模拟以进行单元测试,但是我不确定这是否是用Angular中的参数进行DI的正确方法,而且我也不知道这段代码是否会产生任何意外行为。

虽然我可以将依赖项导入需要它的服务中,并在本地实例化依赖项,但是如果我有很多需要依赖项的服务(和组件),那将非常烦人。

谢谢

0 个答案:

没有答案