Angular 1 promise in service

I went crazy trying to get something to work in Angular 1.3, which might not even be possible ... but it looks like it should be. Basically, I would like to write a service that returns only the calculated value, not a promise.

I have a service that makes a request to $ http.get and returns a promise. I would like to call it from another service, get this data, process it and return the value. I do not want to deal with this, but as soon as I call the service. My reasoning is that I would like to have a sharing function that I can call and get the actual value so that I can use it as a condition for something like ng-show. As I said, I will write this function in the controller and use. Then assign the variable data from the promise, but I do not want to write that in each controller I need it.

Example:

app.factory('searchService', ['$http', function($http) {
  return {
    performSearch: function(searchString) {
      return $http.get('http://asdf.com/search/' + searchString);
    },
    getItemCount: function(itemName) {
      var _this = this;
      this.count = 0;

      this.performSearch(itemName).then(
        function successCallback(resp) {
          _this.count = resp.data.items.length;
        },
        function errorCallback() {
          // This section doesn't matter right now
        };

       return this.count;
    }
  };
}]);

"5" - . , ng-show, , "ng-show =" blahCtrl.getItemCount('item_search_string') == 0 ". , , , , .

, ... , this.count. console.log , () this.count , . , , , ! , , :

var _this = this;
searchService.performSearch('asdf').then(
  function(data) { _this.searchResults.data; }
);

, searchResults . - .

, , , , . ... , .

!

+4
2

, .

app.controller('ctrl', function ($scope, searchService) {
   $scope.searchService = searchService;
   searchService.getItemCount();
});

{{ searchService.count }}

, ng-if, ng-show ..

+1

$q (https://docs.angularjs.org/api/ng/service/ $q). . getItemCount :

app.factory('searchService', ['$http', '$q', function($http, $q) {
  return {
    performSearch: function(searchString) {
      return $http.get('http://asdf.com/search/' + searchString);
    },
    getItemCount: function(itemName) {
      var deferred = $q.defer();

      this.performSearch(itemName).then(
        function successCallback(resp) {
          deferred.resolve(resp.data.items.length);
        },
        function errorCallback(err) {
          deferred.reject(err);
        };

       return deferred.promise;
    }
  };
}]);
0

Source: https://habr.com/ru/post/1658231/


All Articles