我一直在做一个非常简单的应用程序,只是为了试着熟悉一下Angular和Ionic,以及在工作的停机时间里有事可做,我遇到了一个让我有点困惑的问题。这可能是一个非常简单的修复,但我越来越沮丧,试图弄清楚是怎么回事。
上下文
我有一个简单的三页(atm)应用程序,包括登录屏幕,注册屏幕和登陆屏幕,上面有几个操作调用。这个想法是,用户数据(名称,id等)将使用服务(user_svc在这种情况下)持久化,并可用于显示用户特定的东西,这些东西将在稍后从firebase或backand的一些JSON中获取。
问题
我遇到的问题是,无论出于何种原因,这些数据似乎并不是对服务中的所有功能都可用。我让它记录用户对象,我在哪里填充对象,在哪里我试图访问它,并得到以下输出:
服务user_svc的代码在
下面angular.module('app')
.service('user_svc', function($http) {
return {
user: {},
setUser: function(userID) {
$http.get('data/users.json').then(
function(response) {
this.user = response.data.users[userID];
console.log(
'--- SETTER ---' +
'nFETCHED USER:' +
'nID: ' + this.user.id +
'nFORENAME: ' + this.user.forename +
'nSURNAME: ' + this.user.surname
);
},
function(response) {
console.log('File read failed');
}
)
},
getUser: function() {
console.log(
'--- GETTER ---' +
'nFETCHED USER:' +
'nID: ' + this.user.id +
'nFORENAME: ' + this.user.forename +
'nSURNAME: ' + this.user.surname
);
return this.user;
}
}
})
一旦验证了用户的登录,就调用setUser函数,并从我暂时在本地保存的JSON文件中获取信息。它填充了user对象,我本以为这个对象可以被服务中的其他功能访问-这就是服务的意义所在,对吧?遗憾的是,情况似乎并非如此,我也不完全确定原因,所以如果有人能就为什么会发生这种情况提出建议,我将不胜感激。
angular.module('app')
.service('user_svc', function($http) {
return {
user: {},
setUser: function(userID) {
var that = this;// assign this to that
$http.get('data/users.json').then(
function(response) {
// here, this refers to window
// that refers to the this of setUser
that.user = response.data.users[userID];
console.log(
'--- SETTER ---' +
'nFETCHED USER:' +
'nID: ' + that.user.id +
'nFORENAME: ' + that.user.forename +
'nSURNAME: ' + that.user.surname
);
},
function(response) {
console.log('File read failed');
}
)
},
getUser: function() {
console.log(
'--- GETTER ---' +
'nFETCHED USER:' +
'nID: ' + this.user.id +
'nFORENAME: ' + this.user.forename +
'nSURNAME: ' + this.user.surname
);
return this.user;
}
}
})