2016-12-26 8 views
0

角度jでモデルデータを取得しようとしましたが、取得できませんでした。私は春MVCの側に値を印刷しました。データが格納され、正常に取得されたkey.Can誰も私がこれを達成する方法を教えてもらえますか。角度jsコントローラでModelAndViewデータを取得する

マイcontroller-

@RequestMapping(value = "/home.web", method = RequestMethod.GET, produces = { 
      "application/json" }) 

    public ModelAndView getUSCity(@RequestParam ("statechoice") String statechoice) { 


     List<String> msa = new ArrayList<String>();  
     msa = msaService.getMsaCodes(statechoice); 


     /*ModelAndView model = new ModelAndView("Home"); 
     model.addObject("cities",msa); 
    System.out.println(model.getModel().get("cities"));*/ 

     //return msa; 
     return new ModelAndView("Home", "cities",msa); 
    } 

マイ角度JS - あなたが直接cotroller(最良の場合)からのA​​PI呼び出しを行うべきではありませんので、

function MyController($scope, $http) { 

     $scope.getPersonData = function() {   
      $http({ 
       method : 'GET', 
       url : 'home.web' 
      }).success(function(data, status, headers, config) { 
       alert(data); 
       $scope.cities = data; 
      }).error(function(data, status, headers, config) { 
       console.log("error"); 
       // called asynchronously if an error occurs 
       // or server returns response with an error status. 
      }); 

     }; 
    }; 

答えて

0

は、コントローラとサービスにコードを分割します。サービスを使用する必要があります。コントローラは、モデルを制御してビューに表示するためにのみ使用されます。

myService.js

app.service('myService', ['$http', '$q', function($http, $q){ 
    return { 
      getPersons: function(obj) { 
        var deferred = $q.defer();  
        $http({ 
         method : obj.method, 
         url : obj.url 
        }).then(function(response) { 
         deferred.resolve(response); 
        }, function(error) { 
         alert(error); 
         deferred.reject(error); 
         // called asynchronously if an error occurs 
         // or server returns response with an error status. 
        }); 
        return deferred.promise(); 

       }; 
     } 
    }); 

myController.js

function MyController('MyController', ['$scope', 'myService', function($scope, myService){ 
     $scope.persons = []; 
     var obj = {method: 'GET', url: 'home.web'}; 
     myService.getPersons(obj).then(function(response){ 
      $scope.persons = response.data // or $scope.persons = response check yourself 
     }, function(error){ 
      alert(error); 
     }) 
    }]); 
関連する問題