And*_*uze 6 javascript typescript angular
有没有办法编写一个全局自制的mylogger函数,我可以在Angular2 typescript项目中使用我的服务或组件而不是console.log函数?
我想要的结果是这样的:
mylogger.ts
function mylogger(msg){
console.log(msg);
};
Run Code Online (Sandbox Code Playgroud)
user.service.ts
import 'commons/mylogger';
export class UserService{
loadUserData(){
mylogger('About to get something');
return 'something';
};
};
Run Code Online (Sandbox Code Playgroud)
Zyz*_*zle 16
您可以将其编写为服务,然后使用依赖注入使该类可用于您的组件.
import {Injectable, provide} from 'angular2/core';
// do whatever you want for logging here, add methods for log levels etc.
@Injectable()
export class MyLogger {
public log(logMsg:string) {
console.log(logMsg);
}
}
export var LOGGING_PROVIDERS:Provider[] = [
provide(MyLogger, {useClass: MyLogger}),
];
Run Code Online (Sandbox Code Playgroud)
您需要将它添加到应用程序的数组中,将它放在应用程序的顶级注入器中bootstrap
.
import {LOGGING_PROVIDERS} from './mylogger';
bootstrap(App, [LOGGING_PROVIDERS])
.catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
这里有一个非常简单的例子:http://plnkr.co/edit/7qnBU2HFAGgGxkULuZCz?p = preview
接受的答案给出的示例将打印来自logger类的日志MyLogger
,而不是来自实际日志记录的类.
我修改了提供的示例,以便从调用的确切行中打印日志MyLogger.log()
,例如:
get debug() {
return console.debug.bind(console);
}
get log() {
return console.log.bind(console);
}
Run Code Online (Sandbox Code Playgroud)
我在这里找到了如何做到这一点:https://github.com/angular/angular/issues/5458
Plunker:http://plnkr.co/edit/0ldN08?p = preview
根据developers.mozilla中的文档,
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
Run Code Online (Sandbox Code Playgroud)
有关bind
此处的更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
归档时间: |
|
查看次数: |
51400 次 |
最近记录: |