Angular service containing http get call not working with ng-repeat

早过忘川 提交于 2019-12-02 04:12:15

问题


I have an angular controller that calls a service. The service is responsible for returning data from a json file.

controller:

function projectController($scope, ajaxServices) {
$scope.projects = ajaxServices.getProjects();
}

service:

projectManagerApp.factory('ajaxServices', function ($http) {
  return {
    getProjects : function () {
      $http.get('projects.json', { data: {} }).success(function (data) {
      if (window.console && console.log) {
        console.log("objects returned: " + data.length); // shows # of items
      }  
      return data   //nothing ng-repeated, no console errors.
    })
    // Exact same data from json file hard-coded, works fine
    // when not commented out.
    // return [{ "id": 1, "name": "Project 1 }, { "id": 2, "name": "Project 2" }]
    }
   }
});

html: ng-repeat="project in projects"

In the success function I can see the data returned in the console log but if I try to return the data the ng-repeat ul element on my page is empty. In the same service if I simply return the same data logged to the console hard coded (outside of the success function, of course it works just fine.

How can I return the data into the ng-repeat using my ajax call?

I'm just as new to Plunker as I am Angular but here is my attempt at a Plunk: http://plnkr.co/edit/ALa9q6


回答1:


$http is asynchronous, therefore the call to getProjects will return nothing. Using $q you can receive an instance to a promise which will receive the data when available.

Using $q

Here an example using $q: http://plnkr.co/edit/U72oJblvrVEgYt2mTmU2?p=preview

Using $resource

Alternatively, you can use $resource especially if your server code is RESTful, which requires adding the following dependency in your scripts: //ajax.googleapis.com/ajax/libs/angularjs/1.1.4/angular-resource.js

This is a 1st review of your code to use $resource: http://plnkr.co/edit/tLOAaXZHdGgWOok3Sdc8?p=preview

But you can simplify and shrink it more to this: http://plnkr.co/edit/pKO6k6GxJ1RlO8SNvqUo?p=preview

This is the new app.js file:

angular.module('app',  ['ngResource'])
  .factory('ProjectsService', ['$resource', function($resource) {
    return $resource('projects.json');
  }])
  .controller('ProjectsController', ['ProjectsService', '$scope', function(ProjectsService, $scope) {
    $scope.projects = ProjectsService.query();
  }]);

Find more information about $resource here: http://docs.angularjs.org/api/ngResource.$resource




回答2:


You need to use $q. Example is here




回答3:


$http performs asynchronously and may or may not be finished at any given point in time which is why your return statement dont work.

Use $q or simply handle the promise inside the controller:

Service:

projectManagerApp.factory('ajaxServices', function ($http) {
    return {
         getProjects : function () {
            return $http.get('projects.json', { data: {} })           
        }
    }       
});

Controller:

function projectController($scope, ajaxServices) {
    ajaxServices.getProjects().success(function (data) {
        if (window.console && console.log) {
            console.log("objects returned: " + data.length);
        }                          
        $scope.projects = data
    });
}

Plunk




回答4:


If you want data to be loaded before the page Is loaded you can use 'resolve' property For the module. Have a look in the docs for details.



来源:https://stackoverflow.com/questions/20137350/angular-service-containing-http-get-call-not-working-with-ng-repeat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!