2017-01-03 7 views
0

MVCでangularjsを使用しています。角度サービスが値を返しません

ここで私のController.js:

//Get User By ID 
$scope.GetUserById = function (UID) { 
    var Get = UserService.GetUserById(UID); 
    Get.then(function (response) { 
      $scope.User = response.data; 
      alert($scope.User.Address); 
    }); 
}; 

services.js:

//Get By ID 
    this.GetUserById = function (UID) { 
      debugger; 
      return $http.get("../api/UsersData/GetUserById?UID=" + UID); 
    }; 

私は、デバッガを使用している場合は、警告メッセージが表示されます。私がデバッグしていなければ、値を返しません。

私のコードの問題は何ですか?

htmlページに値を表示するにはどうすればよいですか?

+0

'return $ scope.User;'を追加してください。または 'return response.data;'警報の後に。 – rrd

+0

返す約束の 'エラー関数'も実装してみてください。 – ricky

+0

uはコールバック関数を使用しようとしました –

答えて

0

調整はほとんど必要ありません。

Service.js:

angular.module('myApp').factory('MyService', MyService); 

//Avoid Minification Problems 
MyService.$inject = [ '$http' ]; 

function MyService($http){ 

    function GetUserById(UID){ 
     return $http.get('../api/UsersData/GetUserById?UID=' + UID) 
         .then(function (response) { 
      if(response){ 
      return response; 
      } 
     }); 
    } 

    //Expose Method to External Calls 
    return { 
      GetUserById : GetUserById 
    } 

} 

Controller.js:

angular.module('myApp').controller('MyController', MyController); 

MyController.$inject = [ '$scope', 'MyService' ]; 

function MyController($scope, MyService){ 

    $scope.GetUserById = function(UID){ 
    MyService.GetUserById(UID).then(function(response){ 
    $scope.User = response.data; 
    alert($scope.User.Address); 
    }); 
    } 

} 

responseが実際に$logで返すかconsole.logを使用していることを確認し、適切にアドレスを警告するために、 。サービスでもこのチェックを行います。たとえば、response.addressが存在するかどうかを確認する必要があります。

また、代わりに工場サービスを使用することができます。

関連する問題