[英]can't access json object returned from express get route in angular
我有一条快递路线,返回以下JSON
[{"_id":"573da7305af4c74002790733","postcode":"nr22ry","firstlineofaddress":"20 high house avenue","tenancynumber":"12454663","role":"operative","association":"company","hash":"b6ba35492f3f83a79395386cfc601178dfd11de723d2007daf6bd34160a9ff16c87b1f07835e7a39c20454c6271960930211b365ae05c620809c159a3d7b97de","salt":"8d544f21c436494da859cf5895c414d9","username":"yhy","__v":0}]
在我的角度应用程序中,我有一个带有以下代码的工厂
auth.userRole = function() {
alert('here');
if (auth.isLoggedIn()){
return $http.get('/roles/' + auth.currentUser(), {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).then(function(response){
//the info is here, i just can't get to it!!!
return response;
});
}
};
在我的控制器中被称为
$scope.therole = auth.userRole();
我认为我有
我的问题是,当我调试(使用chrome)我的角度时,可以看到响应中包含json(请参见下文),但是我无法访问它! 我尝试过返回return.data或response.data.role或response.role或response [0] .role等的不同排列,这些都不返回空白或导致“属性未定义错误”。 这应该很简单,所以我显然在做一些非常愚蠢的事情。 请帮忙!
Object
config
:
Object
data
:
Array[1]
0
:
Object
__v
:
0
_id
:
"573da7305af4c74002790733"
association
:
"company"
firstlineofaddress
:
"20 high house avenue"
hash
:
"b6ba35492f3f83a79395386cfc601178dfd11de723d2007daf6bd34160a9ff16c87b1f07835e7a39c20454c6271960930211b365ae05c620809c159a3d7b97de"
postcode
:
"nr22ry"
role
:
"operative"
salt
:
"8d544f21c436494da859cf5895c414d9"
tenancynumber
:
"12454663"
username
:
"yhy"
设法通过以下方法解决了我自己的问题:
auth.theUserInfo = function() {
if (auth.isLoggedIn()){
return $http.get('/roles/' + auth.currentUser(), {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).then(function(response){
//the info is here, i just can't get to it!!!
return response.data[0];
});
}
};
response.data [0]返回整个对象。
然后我意识到我的真正问题出在我的控制器中,我只是通过将函数的返回值分配给变量来假设它将把值传回,但是我忘记了它的所有异步特性,所以我不能认为函数会在将返回值分配给变量时得到了结果。 所以我将代码更改为此
auth.theUserInfo().then(function(data) {
$scope.therole = data.role;
});
现在可以使用! 再加上我(现在已重命名)的UserInfo函数现在返回整个对象,而不仅仅是角色,我可以在控制器的其他位置重用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.