[英]Injector not working as expected in Angular2/Ionic2
我已经定义了如下服务:
//storageService.ts
import { Injectable } from '@angular/core';
import {Storage, SqlStorage} from 'ionic-angular';
@Injectable()
export class StorageService {
storage: any;
constructor() {
this.storage = new Storage(SqlStorage);
}
getUser() {
return this.storage.get('user');
}
}
我将其注入另一个类,如下所示:
Profile.ts
import {StorageService} from '../../services/storageService';
@Page({
templateUrl: 'build/pages/profile/profile.html',
providers: [StorageService]
})
export class ProfilePage {
constructor(private http: Http, storageService: StorageService) {
this.storageService.getUser().then(user => {
this.user = JSON.parse(user);
}).catch(error => {
console.log(error);
});
}
}
但是我一直收到错误:
Cannot read property 'getUser' of undefined
由于我将服务注入到构造函数中,所以我收到此错误?
因为您正在使用TypeScript,所以需要在构造函数中将提供程序定义为private
或public
,这将在页面类中自动创建提供程序的实例,例如:
constructor(private http: Http, private storageService: StorageService) {
this.storageService.getUser().then(user => {
this.user = JSON.parse(user);
}).catch(error => {
console.log(error);
});
}
对您问题的其他答复提供了JavaScript解决方案,该解决方案对您不起作用。
据我所知,您需要在Ionic中使用静态parameters
,例如:
@Page({
templateUrl: 'build/pages/profile/profile.html',
providers: [StorageService]
})
export class ProfilePage {
static get parameters() {
return [[Http], [StorageService]];
}
constructor(private http: Http, storageService: StorageService) {
this.storageService.getUser().then(user => {
this.user = JSON.parse(user);
}).catch(error => {
console.log(error);
});
}
}
显然我没有正确使用打字稿。
必须声明如下的storageService:
constructor(private http: Http,private storageService: StorageService) {
即我错过了私人关键字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.