我已按如下方式定义服务:
//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
因为我在构造函数中注入了服务。结果我得到了这个错误?
答案 0 :(得分:1)
因为您使用的是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解决方案。
答案 1 :(得分:0)
据我所知,你需要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);
});
}
}
答案 2 :(得分:0)
显然我错误地使用了打字稿。
必须按以下方式声明storageService:
constructor(private http: Http,private storageService: StorageService) {
即我错过了私有关键字