1

I'm unable to inject a (global) service into another service.

boot.ts

import {bootstrap} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';
import {AppComponent} from './app.component';
import {GlobalService} from './common/global.service';

bootstrap(AppComponent, [
    GlobalService,
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS
]);

global.service.ts

import {Injectable} from 'angular2/core';

@Injectable()
export class GlobalService {
    api_url: string = 'hello';
}

api.service.ts

import {Injectable, Inject} from 'angular2/core';
import {GlobalService} from '../common/global.service';

@Injectable()
export class ApiService {
    //constructor(@Inject(GlobalService) globalService: GlobalService) { // doesnt work
    //constructor(@Inject(GlobalService) public globalService: GlobalService) { // doesnt work
    constructor(public globalService: GlobalService) { // doesnt work
        console.log(globalService); // undefined
        console.log(this.globalService); // undefined
    }

}

It works fine when injecting GlobalService into an Component.

Thank you in advance!

3
  • How is ApiService instantiated? Manually, by Angular (where), by injector.get()? Commented Mar 10, 2016 at 11:48
  • ApiService is a parent class from PageService and ProductService Commented Mar 10, 2016 at 12:49
  • How can I know know what PageService or ProductService is. ApiService needs to be instantiated somewhere. Is it injected somewhere? Did you add it to providers somewhere? Commented Mar 10, 2016 at 12:51

1 Answer 1

1

You need to add ApiService to bootstrap as well

bootstrap(AppComponent, [
    ApiService,
    GlobalService,
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS
]);
Sign up to request clarification or add additional context in comments.

2 Comments

Tried that with no success, still getting "undefined"
You didn't answer yet answer my questions in the comment to your question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.