2013-10-04 74 views
0

這是我迄今爲止很奇怪的問題。 我正在使用jaxon骨幹來完成這個Angularjs項目。AngularJS與澤西JSON資源中未定義在javascript中

  1. Java資源文件

    @GET @Path("{query}") 
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) 
    
    public Signature findByName(@PathParam("query") String query) { 
        return dao.findById(query); 
    } 
    
  2. control.js文件

    function SearchCtrl($rootScope,$scope,Signature) { 
    
    // console.log('SearchCtrl is invoked!!!!!!'); 
        $scope.signature; 
        $scope.searcherrormsg=''; 
    
        $scope.searchaction = function(barcodenum,signature) { 
        signature = Signature.query({rewardcardId:barcodenum}); 
        $scope.signature = signature; 
    
        alert("data is " + $scope.signature.name); <=== This is UNDEFINED 
        }; 
    
    } 
    
  3. apps.js文件

    angular.module('demo', ['demo.filters', 'demo.directives','demo.services.signature']). 
        config(['$routeProvider', function($routeProvider) { 
    
    $routeProvider.when('/search', {templateUrl: 'partials/search.html', controller: SearchCtrl}); 
    $routeProvider.otherwise({redirectTo: '/search'}); 
    
  4. service.js文件

    angular.module('demo.services.signature', ['ngResource']). 
    factory('Signature', function($resource){ 
        return $resource('api/signature/:rewardcardId', {}, { 
        query: {method:'GET', params:{rewardcardId:'signature'}, isArray:false} 
        }); 
    }); 
    

這是調用數據庫和服務器控制檯顯示以下消息;

com.sun.jersey.api.container.filter.LoggingFilter$Adapter finish 
INFO: 1 * Server out-bound response 
1 < 200 
1 < Content-Type: application/json 
1 < 
{"name":"xxx xxxx","customerid":187,"email":"[email protected]","sign":null,"barcode":"xxxx"} 

它會正確顯示HTML頁面的返回數據。例如,html頁面有

<p>{{signature.barcode}} 

{{signature.name}} 

它們正確地顯示名稱和條形碼與上述數據集一樣。

它只有一個問題才能從未定義的javascript中獲取數據。

每當javascript試圖從數據庫返回資源時獲取數據,它就是undefined

回答

2

您正試圖在資源可用之前打印資源。對服務器的請求是異步的。改爲將alert("data is " + $scope.signature.name);代入成功回調。

$scope.searchaction = function (barcodenum, signature) { 
    Signature.query({ rewardcardId: barcodenum }, 
     function(data) { 
      $scope.signature = data; 
      alert("data is " + $scope.signature.name); 
     }, 
     function(err) { // error handling can go here 
    }); 
}; 

我不知道爲什麼你傳遞signature$scope.searchaction,然後在其上執行的賦值操作。

+0

哇!這正是我正在尋找的!非常感謝!你的回答是正確的! – user2845558