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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With