简体   繁体   中英

Inject service in service in Angular2

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!

You need to add ApiService to bootstrap as well

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM