Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Ionic 2: Injection in Service not working

Tags:

angular

ionic2

I'm beginner and playing around with Ionic2 (written on Angular2). I need help to solve a issue with Dependency Injection in my own service.

Here's my code

import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';

@Injectable()
export class Api {
    constructor(public http: Http) {
        console.log('api', http); // http is always undefined.
    }
}


api = new Api();

Other case, it works.

import {Component, View} from 'angular2/angular2';
import {IONIC_DIRECTIVES} from 'ionic/ionic';
import {Http, Headers} from 'angular2/http';
import {Storage, LocalStorage} from 'ionic/ionic';

@Component({
    selector: 'auth-login'
})

@View({
  templateUrl: 'app/auth_login/auth_login.html',
  directives: [IONIC_DIRECTIVES]
})

export class AuthLogin {
  constructor(http: Http) {
    console.log('login', http); // it works
  }
}

Thank you all.

like image 808
Trung Avatar asked Jan 24 '26 09:01

Trung


1 Answers

The injection of services in Ionic go through definition of providers in e.g. @App annotation

http://jbavari.github.io/blog/2015/10/19/angular-2-injectables/

@App({
  templateUrl: 'app/app.html',
  providers: [DataService]
  /* 
    Here we're saying, please include an instance of 
    DataService for all my children components,
    in this case being sessions, speakers, 
    and session detail.
  */
})
class ConferenceApp {
  constructor(platform: Platform, data: DataService) {
    data.retrieveData();
  }
}

This will properly instantiate the service and make it available for injection

like image 139
TomG Avatar answered Jan 25 '26 23:01

TomG