我在打字稿中构建了一个Angularjs提供程序,想知道有没有更好的方法做同样的事情,我的示例提供程序创建了一个控制台记录器的抽象,接口只是为了让编译器满意,并且我在注册表中注册了提供程序代码
module ec{
export interface ILoggerService{
warn(message:string):void;
info(message:string):void;
error(message:string):void;
debug(message:string):void;
log(message:string,exception?:any):void;
}
}
module ec.providers {
export class loggerService {
private loggerState:boolean = false;
public start =() =>{
this.loggerState = true;
}
public $get =['$log',($log:ng.ILogService) =>{
return {
warn:(message) =>{
if(this.loggerState)
$log.warn(message);
},
info:(message) =>{
if(this.loggerState)
$log.info(message);
},
error:(message) =>{
if(this.loggerState)
$log.error(message);
},
debug:(message) =>{
if(this.loggerState)
$log.debug(message);
},
log:(message,exception) =>{
if(this.loggerState)
$log.log(message,exception);
}
}
}]
}
}
module ec{
var app =angular.module('foo',[]).config(['loggerServiceProvider', (loggerServiceProvider)=>{
if(location.hostname =='localhost') {
loggerProvider.start();
}
}]);
app.provider(providers);
}
答案 0 :(得分:2)
module MyNameSpace {
export interface ILoggerService {
warn(message: string): void;
info(message: string): void;
error(message: string): void;
debug(message: string): void;
log(message: string, exception?: any): void;
}
export function loggerService {
var serv = new LoggerService();
this.start = () => {
// ...
};
this.$get = ['$log',($log: ng.ILogService) => {
var methods = ['warn', 'info', 'error', 'debug', 'log'],
obj: any = {};
for (var i = 0; i < methods.length; ++i)
obj[methods[i]] = (msg: string) => $log[methods[i]](msg);
return obj;
}];
}
}
module MyNameSpace {
export interface ILoggerService {
warn(message: string): void;
info(message: string): void;
error(message: string): void;
debug(message: string): void;
log(message: string, exception?: any): void;
}
export function loggerService {
var serv = new LoggerService();
this.start = () => {
// ...
};
this.$get = ['$log',($log:ng.ILogService) => {
serv.start($log);
return serv;
}];
}
class LoggerService implements ILoggerService {
private $log: ng.ILogService;
public start($log: ng.ILogService) {
this.$log = $log;
}
public warn(message) {
if(this.$log)
this.$log.warn(message);
}
// ...
}
}
您可以将provider
替换为service
:
class LoggerService {
private loggerState = false;
static $inject = ['$log'];
constructor(private $log: ng.ILogService) {
}
public start() {
this.loggerState = true;
}
public warn(message) {
if(this.loggerState)
this.$log.warn(message);
}
// ...
}
app.service('LoggerService', LoggerService);