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?

6
  • what problems/errors are you seeing? Commented Jan 21, 2016 at 13:19
  • Is your page also hosted on the same domain (localhost:49358)? Commented Jan 21, 2016 at 13:20
  • you don't have annotation on the GetAllEmployees, is it a typo? Commented Jan 21, 2016 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 localhost:49358 and Angular app gets opened up with a different number. How can I get around that? Commented Jan 21, 2016 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. Commented Jan 21, 2016 at 13:54

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

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.
I updated my answer. I did write a mistake. It should work now.
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
second error I get in IE: Object does not support property or method 'module'
and in Chrome in a debug mode I get the error I do not how to get around it: XMLHttpRequest cannot load localhost:49358/api/myClasses/GetEmployees. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:63799' is therefore not allowed access.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.