簡體   English   中英

無法訪問從表達返回的json對象在角度獲取路由

[英]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(); 

我認為我有

用戶角色是:{{therole}}

我的問題是,當我調試(使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM