简体   繁体   中英

issue with reciving data from WebApi in AngularJs Service

I'm gonna use AngularJS Service in my applications and make everything clean and nice.. I followed some articles for this purpose. but its seems not completed. Right ??
I don't see any error or something but when i set Alert(data); i'll get undefined error. what's my missed work to do here ?

My App.js

var app = angular.module('starter', ['ionic'])

My Service.js

var serverPath = 'http://url/api/locations';

app.service('testService', function($http) {
  this.getLocations = function() {
    $http.get(serverPath).success(function(data) {
      return data;
    });
  };
});

My controller.js

app.controller('LocationsController', function ($scope, testService) {
  $scope.locations = testService.getLocations();
});

and my UI

<div ng-controller="LocationsController">
  <ul>
    <li ng-repeat="location in locations">
      {{ location.locationName }}
    </li>
  </ul>
</div>

You can not get data from asynchronous call directly as soon as you do request for the data. You should follow the promise pattern to deal with asynchronous data.

I'd like to point out several mistakes which you did.

  1. You should have return $http.get promise from the service method getLocations , so that you can place .then function over that method.
  2. Then inside controller call service method getLocations from controller and place .then function, out of which 1st will get call when ajax succeed and 2nd will get called on ajax error. function of .then

     this.getLocations = function () { return $http.get(serverPath); //return promise object }; 

Controller

testService.getLocations().then(function(response){ //success function
     $scope.locations = response.data;
}, function(error){ //error function
     console.log("Some error occurred", error)
});

Here is how I do this since $http has promise inside

I like to add an initialization step to page.

inside Service:

$http.get(serverPath)
  .success(function(data) {
    return data;
  })
  .error(function(err) {
    console.log("some error occured");
    return err;
  });

controller:

app.controller('LocationsController', function($scope, testService) {
  $scope.init = function() {
    testService.getLocations()
      .success(function(res) {
        $scope.locations = res;
      })
      .error(function(err) {
        console.log("LocationsController, getLocations error:", err);
        // alert(err);
      });
  };
});

Markup:

<div ng-controller="LocationsController" ng-init="init()">
  <ul>
    <li ng-repeat="location in locations">
      {{ location.locationName }}
    </li>
  </ul>
</div>

You can also add ng-hide if you the http call take some time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM