kemsbe
kemsbe

Reputation: 605

Angular 2 one service for all app

I need to use logger service in my Angular2 app, but it's rather uncomfortable to write (I'm using ES6 with Angular2):

import { LoggerService } from '../services/logger-service';
...
constructor(@Inject(LoggerService) logger) {
    this.logger = logger;
}

in every component or service where I want to use it. Is there a way to inject LoggerService globally and use anywhere in the app? I haven't found a way to do it.

This is how my logger looks:

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;
        }
    }
}

And example of component where I want to use it in:

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');
    }
}

Upvotes: 0

Views: 498

Answers (1)

eko
eko

Reputation: 40647

One of the solutions is to use Inheritance if you are going to do the same things inside every component.

Your super class would look like:

export abstract class BaseComponent implements OnInit{

 ls:LoggerService;
 constructor(private injector: Injector){
    console.log("I'm super: inside constructor");
    this.ls = this.injector.get(LoggerService);
    this.ls.logger("Super Class log!");
 }
  ngOnInit(){
    console.log("I'm super, inside OnInit");
  }
}

and then you can initialize your super class inside your child classes constructor like this:

constructor(private injector: Injector) {
    super(injector);
  }

you will again need to write the injector inside constructor everytime (and several other bad reasons as mentioned by @Günter here https://stackoverflow.com/a/39038814/5706293) but if you are going to do the same things with this injectable(logger in your case) I think this will be the best solution.

Full example: http://plnkr.co/edit/7qRjjgPI6XvOAzrKhWbV?p=preview

Upvotes: 1

Related Questions