【发布时间】:2016-06-17 21:12:20
【问题描述】:
我定义了一个服务如下:
//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
因为我在构造函数中注入服务..我怎么会收到这个错误?
【问题讨论】:
-
您是否在
@App(...)中添加了providers: [HTTP_PROVIDERS]? -
这里没有HTTP调用
-
不明白你的意思。
constructor(private http: Http,需要它 -
您需要填写您的获取参数()。这个文档页面解释了依赖注入的所有目的:ionicframework.com/docs/v2/getting-started/tutorial/…(检查底部)