在Angular2

时间:2016-03-10 11:46:35

标签: javascript angular

我无法将(全局)服务注入其他服务。

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
    }

}

将GlobalService注入组件时,它可以正常工作。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

您还需要将ApiService添加到bootstrap

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