简体   繁体   English

从Web API将数据获取到Angular应用中

[英]Getting data into Angular app from Web API

I have a Web API where my repository class is: 我有一个Web API,我的存储库类是:

public class myRepository
{

public myClasses.Type[] GetAllTypes()
{

    return new myClasses.Type[]
    {
        new myClasses.Type 
        {
            typeId="1",
            typeVal = "New"
        },
        new myClasses.Type 
        {
            typeId="2",
            typeVal = "Old"
        }
   };

}

public myClasses.Employee[] GetAllEmployees()
{

    return new myClasses.Employee[]
    {
        new myClasses.Employee 
        {
            empId="111111",
            empFName = "Jane",
            empLName="Doe"
        },
        new myClasses.Employee 
        {
            empId="222222",
            empFName = "John",
            empLName="Doe"
        }
   };

}

public bool VerifyEmployeeId(string id)
{

    myClasses.Employee[] emp = new myClasses.Employee[]
    {
        new myClasses.Employee 
        {
            empId="111111",
            empFName = "Jane",
            empLName="Doe"
        },
        new myClasses.Employee 
        {
            empId="222222",
            empFName = "John",
            empLName="Doe"
        }
   };

    for (var i = 0; i <= emp.Length - 1; i++)
    {
        if (emp[i].empId == id)
            return true;
    }
    return false;
}
}

and here is my controller: 这是我的控制器:

public class myClassesController : ApiController
{
private myRepository empRepository;

public myClassesController()
{
    this.empRepository = new myRepository();
}

public myClasses.Type[] GetTypes()
{
    return empRepository.GetAllTypes();
}

public myClasses.Employee[] GetEmployees()
{
    return empRepository.GetAllEmployees();
}

[HttpGet]
public bool VerifyEmployee(string id)
{
    return empRepository.VerifyEmployeeId(string id);
}
}

Now I have created a web application where I included angularJS. 现在,我创建了一个Web应用程序,其中包含了angularJS。 Here is my html (Employees.html) 这是我的html(Employees.html)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Employees</title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="Scripts/angular.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="myClassesApp">
<div ng-controller="myClassesController">
    <table ng-repeat="emp in Employees">
        <tr>
            <td>{{emp.empID}}</td>
            <td>{{emp.empLName}}</td>
        </tr>
    </table>
</div>
</body>
</html>

In my app.js file I have the following: 在我的app.js文件中,我具有以下内容:

var app = angular.module("myClassesApp", []);
app.controller("myClassesController", function ($scope, $http) {
$http.get('http://localhost:49358/api/myClasses/GetEmployees').
    success(function (data, status, headers, config) {
        $scope.Employees = data;
    }).
    error(function (data, status, headers, config) {
        alert('error');
    });
});

Can someone please point me in the right direction in regards to getting data from Web API and displaying it on the page? 在从Web API获取数据并将其显示在页面上方面,有人可以为我指明正确的方向吗?

I see quite some stuff that can be better. 我看到了很多可以改善的东西。

in your app.js, the definition of your controller can be better. 在您的app.js中,控制器的定义可能会更好。 Don't do this: 不要这样做:

var app = angular.module("myClassesApp", []);
app.controller("myClassesController", function ($scope, $http) { 
$http.get('http://localhost:49358/api/myClasses/GetAllEmployees').
    success(function (data, status, headers, config) {
        $scope.Employees = data;
    }).
    error(function (data, status, headers, config) {
        alert('error');
    });
});

Instead, you better do this: 相反,您最好这样做:

  (function(){
    angular.module("myClassesApp", [])
    .controller("myClassesController", myControllerFunction);

myControllerFunction.$inject = ["$scope","$http"];

function myControllerFunction($scope, $http){

  $scope.hello = "hello there";

   $http.get('http://localhost:49358/api/myClasses/GetAllEmployees').
       success(function (data, status, headers, config) {
           $scope.Employees = data;
       }).
       error(function (data, status, headers, config) {
          alert('error');
       });
  };

})();

If you ever want to minimize your code, this with the $inject is the way to go. 如果您想最小化代码,则可以使用$ inject来实现。

Furthermore, don't do this: 此外,请勿执行以下操作:

$http.get('http://localhost:49358/api/myClasses/GetAllEmployees').
    success(function (data, status, headers, config) {
        $scope.Employees = data;
    }).
    error(function (data, status, headers, config) {
        alert('error');
    });

$http service returns a promise. $ http服务返回一个承诺。 Success and error are non-standard angular functions to deal with promises. 成功和错误是处理承诺的非标准角度函数。 However, a better way is this: 但是,更好的方法是这样的:

$http.get('http://localhost:49358/api/myClasses/GetAllEmployees').
    then(function (result) {
        $scope.Employees = result.data;
    }).
    catch(function (error) {
        console.llog(error);
    });

more information (and you really should look into promises), can be found here . 更多信息(您确实应该研究诺言)可以在这里找到。

There is more: You should read into building your own services. 还有更多:您应该阅读构建自己的服务。 It is better practice to move the $http calls away from your controller into your custom made service. 更好的做法是将$ http调用从控制器移到定制服务中。 There are many tutorials on how to do that on the net. 网上有很多关于如何做到这一点的教程。

Then there is also the issue of CORS headers. 然后还有CORS标头的问题。 On your Rest api, you need to assign to your restful resouces which domains can access your resources through XHR calls. 在您的Rest api上,您需要为您的静态资源分配哪些域可以通过XHR调用来访问您的资源。 More information about that can be found here and here is another one . 关于此的更多信息可以在这里找到, 这里是另一个 Then look up how to implement them for the framework/language you are using. 然后查看如何针对您使用的框架/语言实现它们。

One last comment: I hope you realize that with your ng-repeat, you will create a table for each employee, instead of one table filled with employees. 最后一句话:我希望您认识到,通过ng-repeat,您将为每个员工创建一个表,而不是一个充满员工的表。 If you want only one table, you need to do this: 如果只需要一张桌子,则需要执行以下操作:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Employees</title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="Scripts/angular.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="myClassesApp">
<div ng-controller="myClassesController">
    <table>
        <tr ng-repeat="emp in Employees">
            <td>{{emp.empID}}</td>
            <td>{{emp.empLName}}</td>
        </tr>
    </table>
</div>
</body>
</html>

I am not sure if this will help u resolve your particular problem, but i am willing to edit my answer if you can give error messages. 我不确定这是否可以帮助您解决您的特定问题,但是如果您会给出错误消息,我愿意编辑我的答案。 In any way: it should help you write better angular code :-). 无论如何:它应该可以帮助您编写更好的角度代码:-)。

Here is the link to the plunkr: A simple example 这是指向plunkr的链接: 一个简单的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM