0

I have a Web API where my repository class is:

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. Here is my 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:

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?

Coding Duchess
  • 6,445
  • 20
  • 113
  • 209
  • what problems/errors are you seeing? – Henry Zou Jan 21 '16 at 13:19
  • Is your page also hosted on the same domain (http://localhost:49358)? – Henry Zou Jan 21 '16 at 13:20
  • you don't have annotation on the GetAllEmployees, is it a typo? – eesdil Jan 21 '16 at 13:33
  • Henry Zou, I think this is one of the problems - I run both Web API and Anuglar app locally but web api for some reason can only be accessed from http://localhost:49358 and Angular app gets opened up with a different number. How can I get around that? – Coding Duchess Jan 21 '16 at 13:42
  • eesdil, yes, it is a type – Coding Duchess Jan 21 '16 at 13:42
  • 1
    the reason why your web api can only be accessed from localhost:49358 (through javascript XHR calls that is) is because the web api is hosted on that 'domain'. You either host your angular code on the same domain (for example, by putting your angular code in the same project as your web api, that might help) or you look into the CORS headers, and setup your web api with those. If you use the CORS headers, you can specify which domain can access your web api. – ocket-san Jan 21 '16 at 13:54

1 Answers1

1

I see quite some stuff that can be better.

in your app.js, the definition of your controller can be better. 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.

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. 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. There are many tutorials on how to do that on the net.

Then there is also the issue of CORS headers. On your Rest api, you need to assign to your restful resouces which domains can access your resources through XHR calls. 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. 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

Community
  • 1
  • 1
ocket-san
  • 874
  • 12
  • 22
  • Thank you for useful tips! I tried your first suggestion for app.js and gotten a syntax error. I fixed the error but now i am getting others; Uncaught Error: [$injector:modulerr] Failed to instantiate module myClassesApp due to: Error: [$injector:nomod] Module 'myClassesApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. – Coding Duchess Jan 21 '16 at 13:59
  • I updated my answer. I did write a mistake. It should work now. – ocket-san Jan 21 '16 at 14:10
  • To run the app I right-click on my html file and select View in browser. If I open it with IE, which is default, I get an error pop up Angular.js: Line 2789 Error: 'Node' is undefined. If I close the error, I get {{emp.empID}} {{emp.empLName}} on my page. And if I copy and paste html page url into Chrome, I just get {{emp.empID}} {{emp.empLName}} displayed on the page – Coding Duchess Jan 21 '16 at 14:38
  • second error I get in IE: Object does not support property or method 'module' – Coding Duchess Jan 21 '16 at 14:39
  • and in Chrome in a debug mode I get the error I do not how to get around it: XMLHttpRequest cannot load http://localhost:49358/api/myClasses/GetEmployees. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63799' is therefore not allowed access. – Coding Duchess Jan 21 '16 at 14:41
  • The reason why you get {{emp.empID}} {{emp.empLName}} is because you are not getting any data from your web api. The 'Access-Control-Allow-Origin' is a CORS header. I suggest you look into putting those CORS headers on your web api. Look at the links posted in the answer, they should get you on the right track. To be more specific: At the very least you will to add the following headers to your resources: "Access-Control-Allow-Origin", "*" and "Access-Control-Allow-Methods" to specify which http methods are allowed. I don't know how to do that in .net however. i am a java dude :-) – ocket-san Jan 21 '16 at 14:54