Meccuz
Meccuz

Reputation: 3

AngularJS wait for simple promise to be resolved

I'm really new with AngularJS and WebApi and I can't figure out how to wait for promises to be resolved.

I have a very simple application.

This is my HTML code:

<body ng-app="PersonApp">
<div ng-controller="PersonController">
    <div id="personTable">
        <table>
            <tr ng-repeat="p in person">
                <td>{{ p.surname }}</td>
                <td>{{ p.name }}</td>
                <td>{{ p.birthDate | date:'yyyy-MM-dd' }}</td>
                <td>{{ p.fiscalCode }}</td>
                <td>
                    <button type="submit" data-ng-click="edit(p)" class="btn btn-default">Edit</button>
                    <button type="submit" data-ng-click="delete(p)" class="btn btn-default">Delete</button>
                </td>
            </tr>
        </table>
    </div>//.................

My controller:

app.controller('PersonController', ['$scope', 'PersonApp', function ($scope, PersonApp) {
    PersonApp.getPersons($scope);

And finally the service:

app.service('PersonApp', ['$http', function ($http) {
    this.getPersons = function ($scope) {
        return $http({
            method: "GET",
            url: "../api/person",
            headers: { 'Content-Type': 'application/json' }
        }).success(function (data) {
            $scope.person = data;
            console.log(data);
        }).error(function (data) {
            console.log(data);
        });;
    };

I have tried to insert promises everywhere but I really can't figure it out.

I know this is a really dumb question but I hope you have the patience to give me a simple aswer.

Many thanks in advance!

Upvotes: 0

Views: 1173

Answers (1)

Kmart2k1
Kmart2k1

Reputation: 563

You shouldn't inject $scope into your service. The $http service will return a promise. If you modify your PersonApp service to simply return the $http promise, you can assign your $scope.person property in your controller. The code below is untested, but you will understand the basic idea.

PersonApp service

app.service('PersonApp', ['$http', function ($http) {
    this.getPersons = function () {
        return $http({
            method: "GET",
            url: "../api/person",
            headers: { 'Content-Type': 'application/json' }
        });
    };
}]);

PersonController

app.controller('PersonController', function($scope, PersonApp) {
  PersonApp.getPersons().then(function(data) {
      $scope.person = data;
      console.log(data);
  });
});

Here is a link to a working plunker with your code (I faked the $http part since I don't have access to your service).

http://plnkr.co/edit/tpl:rfqcl9AHEoJZEEJxyNn2?p=preview

Here is an article on promises with $http.

http://www.peterbe.com/plog/promises-with-$http

Upvotes: 1

Related Questions