我无法将(全局)服务注入另一个服务。
引导程序
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
]);
全球服务
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注入组件时,它可以正常工作。
先感谢您!
最佳答案
您还需要将ApiService添加到引导程序
bootstrap(AppComponent, [
ApiService,
GlobalService,
ROUTER_PROVIDERS,
HTTP_PROVIDERS
]);