Service Angular2,在另一个服务中使用一个服务

Service Angular2,在另一个服务中使用一个服务,service,angular,Service,Angular,从令人敬畏的响应开始,我想在另一个全局服务(SystemService)中使用许多DataService实例来存储和服务许多“可缓存”数据。 我已导入DataService文件并在全局服务的构造函数中声明DataService类,但在运行时收到错误“EXCEPTION:No provider for DataService!(AppComponent->SystemService->DataService)” 请问,有人能解释一下如何在另一个全球服务中使用该服务吗? 非常感谢 编辑,例如代码 -

从令人敬畏的响应开始,我想在另一个全局服务(SystemService)中使用许多DataService实例来存储和服务许多“可缓存”数据。 我已导入DataService文件并在全局服务的构造函数中声明DataService类,但在运行时收到错误“EXCEPTION:No provider for DataService!(AppComponent->SystemService->DataService)” 请问,有人能解释一下如何在另一个全球服务中使用该服务吗? 非常感谢

编辑,例如代码

---------
// inside bootstrap only the single instance of SystemService
....
bootstrap(AppComponent, [ROUTER_PROVIDERS,HTTP_PROVIDERS,SystemService,provide(LocationStrategy, {useClass: HashLocationStrategy})]).
then((appRef: ComponentRef) => {
    appInjector(appRef.injector);
});

-----------
// chacheable and observable generic Data service, I want to use this class in multiple instances one for each cachable and observable data

import {Injectable} from                                'angular2/core';
import {Http, Response,Headers, RequestOptions} from    'angular2/http';
import {Observable} from                                'rxjs/Observable';
import {Observer} from                                  'rxjs/Observer';    
import                                                  'rxjs/Rx'; 
@Injectable(
export class CacheableData<T> {
    private _apiUrl = 'api/apiweb.php';
    private _params:Object;

    public data: Observable<T>; 
    private _dataObserver: Observer<T>;
    private _data:T;

    constructor (private _http: Http){
        this.data = new Observable(observer => this._dataObserver = observer).startWith(this._data).share();
    }   
    public setParams(_params:Object){
        this._params=_params;
    }   
    public getData(refresh:boolean=false) {     
        if (this._data && !refresh) {
            console.log('CacheableData - getData -> Cache',this._data);
            this._dataObserver.next(this._data);       
        } else {            
            console.log('CacheableData - getData -> HTTP...');

            this._http.post(this._apiUrl,
                    JSON.stringify(this._params),
                    new RequestOptions({ headers: new Headers({'Content-Type': 'application/json'})}))          
                .map(res=><T>res.json().data)
                .do((data) => { })     
                .subscribe(res => {
                    // Update cached data
                    this._data = res;                   

                    console.log('CacheableData - getData -> HTTP',this._data);
                    this._dataObserver.next(this._data);
                }, error => console.log('Could not load data.'))                            

        }
    }
}
---------
// the global service used to cache and retrieve certain type of datas from the server
@Injectable()
export class SystemService{
    constructor (public cacheableData1: CacheableData<IData1>,
             public cacheableData2: CacheableData<IData2>) {

        ....
        this.cacheableData1.setParams({
            manager:"ApiManager",
            action:"GetData1",
            WEB_USER_TOKEN:this.user.Token
        });

        this.cacheableData2.setParams({
            manager:"ApiManager",
            action:"GetData2",
            WEB_USER_TOKEN:this.user.Token
        });
        .....

    }
}


---------
// all views can read and observe chached or fresh data using the systemservice
@Component({
    selector: 'home',
    templateUrl:  'app/components/views/home/home.component.html'
})
export class HomeComponent implements OnInit{   
    public data1:IData1;
    public data2:IData2;

    constructor(private _router: Router,                          
            private _systemService: SystemService) {
    }
    ngOnInit(){

        // data1 observable         
        this._systemService.cacheableData1.subscribe(data => this.data1=data);
        this._systemService.cacheableData1.getData();

        // data2 observable         
        this._systemService.cacheableData2.subscribe(data => this.data2=data);
        this._systemService.cacheableData2.getData(true);

    }   
}
---------
//在bootstrap中,只有SystemService的单个实例
....
引导(AppComponent,[ROUTER_PROVIDERS,HTTP_PROVIDERS,SystemService,Provider(LocationStrategy,{useClass:HashLocationStrategy}])。
然后((appRef:ComponentRef)=>{
appInjector(appRef.injector);
});
-----------
//chacheable and observable generic Data service,我想在多个实例中使用这个类,每个实例对应一个可访问和可观察的数据
从'angular2/core'导入{Injectable};
从'angular2/Http'导入{Http,Response,Headers,RequestOptions};
从“rxjs/Observable”导入{Observable};
从'rxjs/Observer'导入{Observer};
进口“rxjs/Rx”;
@注射的(
导出类可缓存数据{
private _apirl='api/apiweb.php';
私有参数:对象;
公共数据:可观察;
私有数据观察者:观察者;
私有数据:T;
构造函数(私有的http:http){
this.data=新的可观察对象(observer=>this.\u dataObserver=observer).startWith(this.\u data.share();
}   
公共setParams(_params:Object){
这个。_参数=_参数;
}   
publicGetData(刷新:boolean=false){
如果(此._数据&&!刷新){
log('CacheableData-getData->Cache',this.\u data);
this.\u dataObserver.next(this.\u data);
}否则{
log('CacheableData-getData->HTTP…');
this.\u http.post(this.\u apirl,
JSON.stringify(this._参数),
新的RequestOptions({headers:newheaders({'Content-Type':'application/json'})}))
.map(res=>res.json().data)
.do((数据)=>{})
.订阅(res=>{
//更新缓存数据
这是._data=res;
log('CacheableData-getData->HTTP',this.\u data);
this.\u dataObserver.next(this.\u data);
},error=>console.log('无法加载数据'))
}
}
}
---------
//用于从服务器缓存和检索特定类型数据的全局服务
@可注射()
导出类系统服务{
构造函数(公共cacheableData1:CacheableData,
公共cacheableData2:CacheableData){
....
this.cacheableData1.setParams({
经理:“ApiManager”,
操作:“GetData1”,
WEB\u用户\u令牌:this.USER.TOKEN
});
this.cacheableData2.setParams({
经理:“ApiManager”,
操作:“GetData2”,
WEB\u用户\u令牌:this.USER.TOKEN
});
.....
}
}
---------
//所有视图都可以使用systemservice读取和观察更改或新数据
@组成部分({
选择器:“主页”,
templateUrl:'app/components/views/home/home.component.html'
})
导出类HomeComponent实现OnInit{
公共数据1:IData1;
公开数据2:IData2;
构造器(专用路由器:路由器、,
私人(系统服务:系统服务){
}
恩戈尼尼特(){
//数据1可观测
this.\u systemService.cacheableData1.subscribe(数据=>this.data1=data);
这是.u systemService.cacheableData1.getData();
//数据2可观测
this.\u systemService.cacheableData2.subscribe(数据=>this.data2=data);
这是._systemService.cacheableData2.getData(true);
}   
}
当然我错过了一些东西,但概念是我需要一个SystemService的全局实例,它使用多个不稳定的CacheableData服务,以便为所有视图和页面提供可观察和可缓存的数据……或者为其他服务提供可观察和可缓存的数据,为什么不呢。 我无法将CacheableData添加到bootstrab,因为我需要多个实例,但如果我不需要,我会收到错误消息,即缺少提供程序。。。
请原谅代码不完整,但我的项目相当复杂。…

根据范围,您要使用的每个服务都必须添加到提供者数组中

引导中调用:

bootstrap(AppComponent[
...,
全球服务,
数据服务
]);
或者在根组件中:

@组件({
...,
提供者:[……,全球服务,数据服务]
})
导出类AppComponent{…}

您是否检查了循环引用,例如服务A使用服务B,服务B使用服务A?我最近遇到了此类问题,错误消息与您的相同。

感谢您的回答,问题是在SystemService中,我需要多个不同的DataService实例来更改mul多个不同的数据。将DataService添加到引导只会创建一个实例,如果我有错误,请纠正我。如何有多个DataService?您将在哪里实例化它们?能否添加演示您尝试的代码?