Angular 4 NgModule - 将具有目标类名称的服务注入到另一个服务中

时间:2017-06-07 20:04:38

标签: angular typescript dependency-injection

我想知道在Angular 4依赖注入期间是否有办法访问目标类名。我试图这样做,因为我希望我的日志记录系统知道日志记录的来源并打印它,而不必每次都指定它。

这是我的问题的一些背景:

这是我的记录器的片段

@Injectable()
export class Logger {
    constructor(private source: string, (...)) { }
}

这是我服务的一小部分

@Injectable()
export class SomeService {
    constructor(private logger: Logger, (...)) {
        // I know i could initialize the logger here and set the name of the service, but I would like to do it by injection, if possible
    }
}

我想做什么

export function factoryFunc() {
    return (injectionContext : InjectionContext): string => {

        /* InjectionContext doesn't exist, its just theorical and to explain
           what I'm trying to achieve, which is to access an injection context in
           the factory func and the target class name
        */
        var className = injectionContext.getInjectionTargetClassName();
        return new Logger(className);
    };
};


@NgModule({
    (...),
    providers: [
        SomeService,
        { provide: Logger , useFactory: factoryFunc() },
    ]
})

0 个答案:

没有答案