2015-12-14 62 views
0

我在Angular上創建了一個登錄控制器,並且我有一個工廠服務,在該服務中我發送了一個post請求並返回json數據。當我console.log成功的數據,我可以看到一個對象,但是當我嘗試訪問屬性我得到未定義。如何在成功後從服務器顯示json?

UserAuthFactory.login(name,password) 
     .success(function(data){ 
      console.log(data.token); 
      AuthenticationFactory.token = data.token; 
      console.log(data); 
     }).error(function(status){ 
      console.log('oops something went wrong.'); 
     }); 
}; 

在我的console.log

對象{成功:真的,消息: 「盡情享受您的令牌」,令牌: 「eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1N ... jowfQ.Hcfejg7x7W4w01fBaf303I2iJ57T38e84vLtGDiwSHI」} 消息:「享受你的令牌!「的成功:truetoken: 」eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NjUzODEyNjg2NzFhM2JhMmQ2NTQ4NjgiLCJuYW1lIjoiTmljayBHbG9uYXJpcyIsInBhc3N3b3JkIjoicGFzc3dvcmQiLCJhZG1pbiI6dHJ1ZSwiX192IjowfQ.Hcfejg7x7W4w01fBaf303I2iJ57T38e84vLtGDiwSHI「 : Object app.js:121 undefined

我該如何訪問數組的不同屬性?諸如令牌,消息等屬性?

+0

變種jsData = JSON.parse(數據); console.dir(jsData); – magreenberg

+0

[Parse JSON in JavaScript?](http://stackoverflow.com/questions/4935632/parse-json-in-javascript) – Stewartside

回答

0

當你有一個JSON對象,你應該只與函數轉換它 JSON.parse(文本)

例如

var json_object = JSON.parse(json_string); 
console.log(json_object.parameter); 
+0

這是我需要的,謝謝。 – arsenalist

1

如果你想訪問HTML部分數據,請參閱我的示例代碼。

我沒有使用$ scope,$ http模塊。

example.controller('Example', function($scope, $http) { 

    $scope.token = ''; 
    $scope.message = ''; 
    $scope.etc = null; 

    $scope.getToken = function() { 

     var reqParams = { id: 'userid', password: 'owije3wefo' }; 
     $http.post('getToken', reqParams).then(function(res) { 

      console.log(res.data); 
      this.result = res.data.token; 
      this.message = res.data.message; 
      this.etc = res.data.etc; 

     }.bind(this)); 
    }; 
}); 

在HTML中,

<div ng-controller="Example"> 
    <div> 
     <span class="label">token</span> 
     <input ng-model="token" type="text" /> 
    </div> 
</div> 
相關問題