2015-01-05 2 views
0

У меня есть трудное время, чтобы узнать, как получить возвращаемое значение от службыПолучить значение, возвращаемое из angularjs службы

categoryService:

angular.module("thethaoso").service("categoryService", ['$http', '$q', function ($http, $q) { 
    return ({ 
     getCatId: getCatId 
    }); 
    function getCatId(sename) {  

     var request = $http.get('/api/category/' + sename); 
     return request.then(handleSuccess, handleError); 
    } 

    function handleError(response) { 
     if (!angular.isObject(response.data) || 
      !response.data.message 
      ) { 

      return ($q.reject("An unknown error occurred.")); 
     } 
     // Otherwise, use expected error message. 
     return ($q.reject(response.data.message)); 

    } 
    // I transform the successful response, unwrapping the application data 
    // from the API response payload. 
    function handleSuccess(response) { 
     return (response.data); 
    } 

}]); 

вызова из контроллера:

 categoryService.getCatId(sename).then(function (Id) { 
       $scope.categoryId=Id; 
      }); 

console.log($scope.categoryId) >> undefined, i guess the service is not yet completed. 
$scope.$on('tabParent', function (event, data) { 
       console.log('hello'); **>> get the message** 
       anotherService.abc($scope.categoryId) .... **>> fail** 
      }); 

Я пробую $ timeout с 2000-3000 мс, это работает, но это было бы слишком поздно

также я попытался поставить $ объем $ на внутри categoryService, но он никогда не называет

categoryService.getCatId(sename).then(function (Id) { 
      $scope.categoryId=Id; 
      $scope.$on('tabParent', function (event, data) { 
       console.log('hello'); >> **>> never reach** 
       anotherService.abc($scope.categoryId) .... **>> fail as above** 
      } 
     }); 
     }) 

.

Какой самый быстрый способ получить возвращаемое значение за пределами Затем блок или лучший способ переписать categoryService?

ответ

0

вам нужно сделать журнал консоли внутри функции обратного вызова then,

categoryService.getCatId(sename).then(function (Id) { 
      $scope.categoryId=Id; 
      console.log($scope.categoryId) 
}); 
+0

Затем нам нужно более подробно о том, где вы вызываете функцию ('' emit' или broadcast'). Похоже, вам нужно подождать, пока загрузится «categoryId». –

Смежные вопросы