Luke Frauhiger Luke Frauhiger - 2 months ago 9
TypeScript Question

Can't I import an Injectable class as service

I"m building an app with Ionic 2 and have come across a problem. Any help would much appreciated.

I am using a service called

plan-data.ts
to get and post data to a firebase database.The problem I'm running into is that when I try to import and declare the
plan-data.ts
file on a few specific components, it errors out. On the page below it is working fine!

**DASHBOARD.ts**
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { PlanData } from '../../providers/plan-data/plan-data';

@Component({
templateUrl: 'build/pages/dashboard/dashboard.html',
providers: [PlanData]
})
export class DashboardPage {

constructor(private navCTRL: NavController, public planData: PlanData){
this.planData = planData;
this.loadList();
}
...
}


But on this file, when I try to import and declare it as a
provider
, it fails with an error of:
Cannot read property 'parameters' of undefined
.

**STOPWATCH.ts**
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { PlanData } from '../../providers/plan-data/plan-data';

@Component({
templateUrl: 'build/pages/watch-calc/watch-calc.html',
providers: [PlanData]
})
export class WatchCalcPage {

constructor(private navCTRL: NavController, public planData: PlanData) {
this.planData = planData;
}


I can't seem to figure out what is different or wrong on the second page and can't seem to find anyone having this issue which means it's probably me no seeing something simple. And suggestions would be very helpful, thank you!

Answer

I am using a service called plan-data.ts to get and post data to a firebase database

Do you intentionally want to create a new instance of the PlanData class in each page? By adding it in the providers array of both DashboardPage and WatchCalcPage, a different instance will be created for each page.

In order to use the same instance in the entire app, you should include the PlanData class in the providers array of the top-most component like this:

@Component({
  templateUrl: 'build/app.html',
  providers: [PlanData, ...]
})
export class MyApp { ... }

And then just include it in the constructor

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { PlanData } from '../../providers/plan-data/plan-data';

@Component({
  templateUrl: 'build/pages/watch-calc/watch-calc.html'
})
export class WatchCalcPage {

  constructor(private navCTRL: NavController, public planData: PlanData) {
    // this.planData = planData; <- you don't need to do this; it's done automatically by typescript because it's included as a parameter in the constructor.
  }
Comments