I am studying angularjs and web.api v2 and to call a simple API to get list of Contacts, using below code:
$scope.GetAllContacts = function () {
$http.get('http://localhost:50820/api/contacts').
success(function (data, status, headers, config) {
$scope.contacts = data;
// OUT PUT WILL BE [{contact1},{contact2},....]
}).
error(function (data, status, headers, config) {
alert("couldn't get contacts.");
});
}
each contact object has (ID,Name,Lastname,Email).
and this is my HTML page
<content ng-controller="ContactController">
<table border="1">
<tr ng-repeat="contact in contacts">
<td>{{contact.Id}}</td>
<td>{{contact.Name}}</td>
<td>{{contact.LastName}}</td>
<td>{{contact.Email}}</td>
</tr>
</table>
</content>
Problem happens when API returns only 1 record, like {contact1} Like this {"Id":1,"Name":"James","LastName":"Oliver","Email":"[email protected]"}
at this point angularjs will treat it as a JSON object with 4 records, like this [{ID},{Name},{Lastname},{Email}]
and therefore Ng-Repeater is not able to find, contact.id , contact.name, contact.lastname or contact.email.
I am not sure, is it because of ASP.Net API returning wrong format, or I need to use another method ??
I have already tried JSON.parse and Angular.toJson but didn't work.
Found out the issue, I had two different method,
GetAllContacts() //returns a collection of contacts
GetContact(int id) // return a single contact object
in fiddler both of the responses was OK, as they are detected as JSON object, but Ng-Repeater was taking the single object as a JSON with 4 object (because of 4 property), instead of treating it as one object.
so what I did, was to put the single contact object, in a collection and return the result as a collection with only one record. and It solved the problem.