Andris Krauze Andris Krauze - 4 months ago 477
Javascript Question

How to write console.log wrapper for Angular2 in Typescript

Is there a way to write a global selfmade mylogger function that I could use in Angular2 typescript project for my services or components instead of console.log function ?

My desired result would be something like this:

mylogger.ts

function mylogger(msg){
console.log(msg);
};


user.service.ts

import 'commons/mylogger';
export class UserService{
loadUserData(){
mylogger('About to get something');
return 'something';
};
};

Answer

You could write this as a service and then use dependency injection to make the class available to your components.

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}),
    ];

You'll want to place this in the top level injector of your application by adding it to the providers array of bootstrap.

import {LOGGING_PROVIDERS} from './mylogger';

bootstrap(App, [LOGGING_PROVIDERS])
  .catch(err => console.error(err));

A super simple example here: http://plnkr.co/edit/7qnBU2HFAGgGxkULuZCz?p=preview