通过单独的服务使用web api处理角度时,我无法获取数据

时间:2017-05-22 13:12:05

标签: angularjs asp.net-web-api

从服务器获取数据的是services.js文件。我有主脚本文件,虽然没有将数据导入主java脚本方法表单服务层。

  

块引用

请检查代码,如果我有任何错误,请告诉我:

app.factory("studentServices", function ($http)## 



----------


 ##
 return {

        postData: function (student) {

            $http.post("/api/Student/Register", student)
              .then(function (response) {
                console.info(response.data);

                debugger;
                return response.data;

            }, function (error) {

                console.info("error in reruest");
            });
        },
        getData: function () {
            debugger;
            var rt;
            $http.get("/api/Student/getStudent").then(function (response) {
                console.info(response.data);
                debugger;
                rt=response.data;
            }, function (error) { console.info("error in geting"); })
            debugger;
            return rt;
        }

        }
    })

"这是工厂的其他服务"

/// <reference path="../Scripts/angular.js" />
/// <reference path="script.js" />
var app = angular.module("myModule", []).controller("myController", function ($scope, $http, studentServices) {
    debugger;
    console.info("init");

    $scope.addStudent = function () {
        console.info("just");
        console.info($scope.id);
        $scope.result="";
        var student = {id:$scope.id,name:$scope.name,email:$scope.email,college:$scope.college,mobile:$scope.mobile}
        console.info(student);
      //  $http.post("/api/Student/Register", student).then(function (response) {
        //    console.info(response.data);
        $scope.result = studentServices.postData(student);
            console.info("result " + $scope.result);
            get();
       // }, function (error) { console.info("error in reruest") })
        //$scope.getStudents();
    }


    $scope.getStudents = function get() {
        debugger;
            console.info("gettinf studetn list");
        //    $http.get("/api/Student/getStudent").then(function (response) {
        //      console.info(response.data);
            var local = studentServices.getData();
            debugger;
            $scope.students = local;  //response.data;
            debugger;
            console.info("getdata list  ");

    //        }, function (error) { console.info("error in geting") })

        }
        console.info("last");

})

1 个答案:

答案 0 :(得分:0)

您需要纠正以下事项:

1.在您的工厂方法中,只需返回api承诺。例如:

postData: function (student) { 
    return  $http.post("/api/Student/Register", student);
}

2.在您的控制器中使用工厂方法及其响应: 例如:

studentServices.postData(student).then(function (result){    
    $scope.result = result.data;
}, function(error){
    // handle error
})

getData执行类似操作。

由于$http是异步的,您必须解析控制器中的数据,因此获取数据。见fiddle