Angular Service不返回值

时间:2017-01-03 09:24:03

标签: angularjs model-view-controller asp.net-web-api

我在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页面?

1 个答案:

答案 0 :(得分: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是否存在。

您还可以使用服务代替工厂