2

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.

2 Answers 2

1

I think you can check the data you are receiving in response from web service,inside the success function.

console.log(data);

if it print in below format then ng-repeater will be able to find the individual object.

[{"Id":1,"Name":"James","LastName":"Oliver","Email":"[email protected]"}]

But if you receive the data like below.

{"Id":1,"Name":"James","LastName":"Oliver","Email":"[email protected]"}

Then ng-repeater won't be able to find it (May be you should check your server side then).

See i did a quick test at JSFiddle

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

Comments

1

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.

Comments

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.