【发布时间】:2017-04-13 21:44:30
【问题描述】:
我需要在我的 Angular2 应用程序中使用记录器服务,但是写起来很不舒服(我正在使用 ES6 和 Angular2):
import { LoggerService } from '../services/logger-service';
...
constructor(@Inject(LoggerService) logger) {
this.logger = logger;
}
在我想使用它的每个组件或服务中。有没有办法全局注入LoggerService 并在应用程序的任何地方使用?我还没有找到方法。
这是我的记录器的外观:
import {Injectable} from '~/node_modules/@angular/core';
@Injectable()
export class LoggerService {
constructor() {
if (appConfig.dev) {
this.log = console.log.bind(console);
this.error = console.error.bind(console);
this.info = console.info.bind(console);
} else {
this.log = this.error = this.info = () => null;
}
}
}
以及我想在其中使用它的组件示例:
import { Component, Inject } from '~/node_modules/@angular/core';
import { LoggerService } from '../services/logger-service';
@Component({
'selector': 'activities',
'template': template,
'styles': [style]
})
export class ActivitiesComponent {
constructor(@Inject(LoggerService) logger){
this.logger = logger;
}
someAction() {
this.logger.log('hello');
}
}
【问题讨论】:
-
有一些技巧,但我认为你不应该使用它们,只需将它注入你需要的地方。
-
使用继承怎么样?
-
@GünterZöchbauer 你能提供一些例子吗?即使它是 hacks 方式,它也可以帮助未来的读者和我更好地理解 Angular 2 DI 苯乙烯?
-
@echonax 你能举个例子吗?可能只有几行,我现在有点看不懂
-
我想这是stackoverflow.com/questions/39038791/… 我猜还有一个,但我没找到。
标签: angular logging dependency-injection