获取angularjs服务返回的值

时间:2015-01-05 04:40:40

标签: angularjs angularjs-service

我很难知道如何从服务中获取价值

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**
          });

我尝试使用2000-3000毫秒的$ timeout,它可以工作但是为时已晚

我也尝试将$ scope。$放在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的更好方法?

1 个答案:

答案 0 :(得分:0)

您需要在then回调函数

中执行控制台日志
categoryService.getCatId(sename).then(function (Id) {
           $scope.categoryId=Id;
           console.log($scope.categoryId) 
});