简体   繁体   English

在Ionic 2中将服务注入另一个服务

[英]Injecting a service into another service in Ionic 2

I'm starting with Ionic 2 and I had a problem straight away. 我从Ionic 2开始,我马上就遇到了问题。 I'm doing some tests trying to replicate an Angular 2 application already working. 我正在尝试复制已经工作的Angular 2应用程序。

The problem comes when I try to use a service inside another service. 当我尝试在另一个服务中使用服务时出现问题。

I have a data.service.ts which uses Http service and provides a little extra functionality, and this service will be used by all my other specialized services. 我有一个data.service.ts,它使用Http服务并提供一些额外的功能,这项服务将被我所有其他专业服务使用。

So this is 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());
    }
  }

}

And this is another service, schedules.service.ts, which basically uses data.service.ts to get some json file and do some stuff on the data recovered. 这是另一个服务,schedules.service.ts,它基本上使用data.service.ts来获取一些json文件并对恢复的数据做一些事情。

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;
        });
      });
  }

}

Now, in my Angular 2 app this is working, because I'm using modules, and in the module for the schdules I'm also importing a sharedModule, which contains DataService. 现在,在我的Angular 2应用程序中,这是有效的,因为我正在使用模块,而在模块中,我还要导入一个包含DataService的sharedModule。

@NgModule({
  imports: [ 
    routing,
    SharedModule.forRoot()
  ],
  declarations: [
    //...
  ],
  providers: [ SchedulesService ]
})
export class SchedulesModule { }

and sharedModule 和sharedModule

@NgModule({
  imports: [ 
    CommonModule,
    HttpModule
  ],
  declarations: [ 
    //...
  ],
  exports: [
    //...
  ]
})
export class SharedModule {

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [ 
        DataService
      ]
    };
  }
}

BUT, in Ionic 2 I'm not using modules and when I try to use execute my previous code I get a TypeError: Cannot read property 'get' of undefined 但是,在Ionic 2中我没有使用模块,当我尝试使用执行我以前的代码时,我得到一个TypeError: Cannot read property 'get' of undefined

The line with the error is this one: 出错的行是这一行:

return this.http.get(url)
            .map(response => response.json());

I'm guessing the Http is undefined because is not instantiated, and that might be because is not being injected in the ScheduleService. 我猜测Http是未定义的,因为没有实例化,这可能是因为没有在ScheduleService中注入。 Is that correct? 那是对的吗? Any idea on how to fix this? 有关如何解决此问题的任何想法?

EDIT. 编辑。 Ok, a few things I was missing. 好的,我遗失了一些东西。 The home.ts which is using the SchedulesService actually has the DataService in the providers attribute of the @Component, so I think thi is working fine and the issue should not be related to the injection. 使用SchedulesService的home.ts实际上在@Component的providers属性中有DataService,所以我认为这个工作正常,问题不应该与注入有关。 Any idea? 任何想法?

@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());
   ...
  }
  ...

I had a similar (or even the same?) problem when working on my Ionic 2 app. 在我的Ionic 2应用程序上工作时,我遇到了类似的问题(甚至相同的问题)。 It created a new instance of the shared service every time I used it in another provider. 每次我在另一个提供程序中使用它时,它都会创建一个新的共享服务实例。

Seems like I just had to remove it from providers in my app.components.ts: 好像我只需要从我的app.components.ts中的提供程序中删除它:

@Component({
    templateUrl: 'app.html',
    providers: [], 
})

For more information you can see my forum post in the ionic forum: https://forum.ionicframework.com/t/shared-service-in-other-provider/72499/3 有关更多信息,您可以在离子论坛中查看我的论坛帖子: https//forum.ionicframework.com/t/shared-service-in-other-provider/72499/3

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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