私はIonic 2から始めていますが、すぐに問題がありました。すでに動作しているAngular 2アプリケーションを複製しようとするいくつかのテストを行っています。Ionic 2の別のサービスにサービスを注入する
問題は、別のサービス内でサービスを使用しようとしたときに発生します。
私は、Httpサービスを使用するdata.service.tsを持っており、少し余分な機能を提供しています。このサービスは私の他のすべての専門サービスで使用されます。
だから、これはdata.service.ts
import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class DataService {
constructor(private http:Http) {
}
getJson(url: string, update: number) {
if (update !== -1) {
return Observable.timer(0, update)
.flatMap(() => this.http.get(url))
.map(response => response.json());
} else {
return this.http.get(url)
.map(response => response.json());
}
}
}
であり、これは基本的には、いくつかのJSONファイルを取得し、上のいくつかのものを行うためにdata.service.tsを使用して別のサービス、schedules.service.ts、ありますデータが回復しました。
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Rx";
import { DataService } from './data.service';
@Injectable()
export class SchedulesService {
// this will be changed with Constants.ts
private DATA_PATH = '/resources';
private UPDATE_INTERVAL_DATA = 120000;
//private schedules: Schedule[];
private schedules: any[];
private url = `//localhost${ this.PATH }/data.json`;
constructor(
private dataService: DataService) {
}
loadSchedules() {
return this.dataService
.getJson(this.url, this.UPDATE_INTERVAL_DATA)
.map(data => {
return data.schedules.list.map(item => {
// do some stuff..
return item;
});
});
}
}
私はモジュールを使用していますので、今、私の角度2のアプリでは、これは、働いている、とschdulesためのモジュールで、私はまたのDataServiceが含まれているsharedModuleを、インポートしています。
@NgModule({
imports: [
routing,
SharedModule.forRoot()
],
declarations: [
//...
],
providers: [ SchedulesService ]
})
export class SchedulesModule { }
とsharedModule
@NgModule({
imports: [
CommonModule,
HttpModule
],
declarations: [
//...
],
exports: [
//...
]
})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
DataService
]
};
}
}
しかし、イオン2に私は、モジュールを使用していないと私は私の以前のコードを実行使用しようとすると、私はTypeError: Cannot read property 'get' of undefined
エラーのある行を取得しますこれは1:
return this.http.get(url)
.map(response => response.json());
私は、HTTPを推測しているインスタンス化されていないため、未定義です、それはScheduleServiceに注入されていない可能性があります。あれは正しいですか? これを修正する方法はありますか?
EDIT。さて、いくつか私は行方不明だった。 SchedulesServiceを使用しているhome.tsは、実際に@Componentのproviders属性にDataServiceを持っています。そのため、この問題はうまく機能していると思います。何か案が?
@Component({
templateUrl: 'build/pages/home/home.html',
providers: [ SchedulesService, DataService ]
})
export class HomePage {
private schedules: any[];
constructor(
private schedulesService: SchedulesService,
private commonCodesService: CommonCodesService,
private dataService: DataService) {
}
getSchedules() {
...
this.schedulesService
.loadSchedules()
.subscribe(() => this.updateSchedules());
...
}
...
解決しましたか、回避策を見つけましたか? – nyluje