我是初学者,玩Ionic2(写在Angular2上)。我需要帮助来解决我自己的服务中的依赖注入问题。
这是我的代码
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();
其他情况,它有效。
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
}
}
谢谢大家。
答案 0 :(得分:3)
Ionic中的服务注入通过以下方式定义提供者: @App注释
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();
}
}
这将正确地实例化服务并使其可用于注射
答案 1 :(得分:1)
您必须将服务声明为您要使用的地方
@Component({
selector: 'auth-login',
providers: [Api]
})
答案 2 :(得分:0)
我在使用Ionic 2和Angular 2时遇到了类似的问题。我有一个app.ts和一个login.ts以及一个user-data.ts(就像你的api.ts一样)。
app.ts< - login.ts< - user-data.ts
当我将UserData类作为提供程序放在login.ts和app.ts中时,一切都开始工作了。
app.ts 是这样的:
@Component({
templateUrl: 'build/app.html',
directives: [ROUTER_DIRECTIVES],
providers: [
{
provide: TranslateLoader,
useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
deps: [Http]
},
TranslateService,
ROUTER_PROVIDERS,
UserData
]
})
login.ts 就像这样
import {Page, NavController} from 'ionic-angular';
import {UserData} from '../../providers/user-data-provider/user-data';
@Page({
templateUrl: 'build/pages/login/login.html',
providers: [UserData]
})
export class LoginPage {
...
}
和 user-data.ts 就像这样
import {Injectable} from '@angular/core';
import {Storage, LocalStorage, Events} from 'ionic-angular';
@Injectable()
export class UserData {
...
}
我正在使用:
C:\ionic2\myapp>npm list -depth=0
+-- @angular/common@2.0.0-rc.3
+-- @angular/compiler@2.0.0-rc.3
+-- @angular/core@2.0.0-rc.3
+-- @angular/forms@0.1.1
+-- @angular/http@2.0.0-rc.3
+-- @angular/platform-browser@2.0.0-rc.3
+-- @angular/platform-browser-dynamic@2.0.0-rc.3
+-- @angular/router@2.0.0-rc.2
+-- cordova@6.3.0
+-- del@2.2.0
+-- es6-shim@0.35.1
+-- gulp@3.9.1
+-- gulp-watch@4.3.5
+-- ionic-angular@2.0.0-beta.10
+-- ionic-gulp-browserify-typescript@2.0.0
+-- ionic-gulp-fonts-copy@1.0.0
+-- ionic-gulp-html-copy@1.0.0
+-- ionic-gulp-sass-build@1.0.0
+-- ionic-gulp-scripts-copy@2.0.1
+-- ionic-gulp-tslint@1.1.0
+-- ionic-native@1.3.2
+-- ionicons@3.0.0
+-- ng2-bootstrap@1.0.17
+-- ng2-translate@2.2.2
+-- reflect-metadata@0.1.3
+-- run-sequence@1.1.5
+-- rxjs@5.0.0-beta.6
+-- tslint-ionic-rules@0.0.3
`-- zone.js@0.6.12
希望有所帮助