刷新角度数据ASP Net Web服务

时间:2019-02-26 23:18:48

标签: javascript c# asp.net angularjs

我开始在ASP网络中学习angularJS,因此我可以实现一些每x异步刷新一次的数据绑定,并避免使用更新面板。我设法使数据绑定起作用,这是我的代码。

    <head runat="server">
    <title></title>

    <script src="Scripts/angular.min.js"></script>  

    <script>

        var app = angular.module("myModule", []).controller("myController",
            function($scope, $http) {

  $http.get("UsersService.asmx/GetAllUsers").then(function(response) {

                    $scope.users = response.data;

                });
            });

    </script>

</head>
<body ng-app="myModule">
    <form id="form1" runat="server">
    <div ng-controller="myController">

       <table>
           <thead>
               <tr>
                   <th>ID</th>
                   <th>Username</th>
                   <th>Password</th>
                   <th>LastLogin</th>
               </tr>
           </thead>
           <tbody>
               <tr ng-repeat="user in users">
                   <td>{{ user.ID }}</td>
                   <td>{{ user.Username }}</td>
                   <td>{{ user.Password }}</td>
                   <td>{{ user.LastLogin }}</td>
               </tr>
           </tbody>
       </table>

    </div>
    </form>
</body>
</html>

和网络服务

        [WebMethod]
        public void GetAllUsers()
        {
            List<User> listUsers = new List<User>();
            string cs = ConfigurationManager.ConnectionStrings["AngularJS_ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users", con))
            {
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        User user = new User();
                        user.ID = Convert.ToInt32(sdr["UserID"]);
                        user.Username = sdr["Username"].ToString();
                        user.Password = sdr["Password"].ToString();
                        user.LastLogin = sdr["LastLogin"] as DateTime?;
                        listUsers.Add(user);
                    }
                }
            }

            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(listUsers));
        }

我的问题是,例如,我如何才能使Web服务每x次调用一次,并使用ajax和angular js在页面上刷新?

1 个答案:

答案 0 :(得分:1)

在JavaScript中使用setInterval

//first argument is function to call in interval
setInterval(function () {
    $http.get("UsersService.asmx/GetAllUsers").then(function (response) {

        $scope.users = response.data;
    }
}, 1000); //milliseconds