我很难知道如何从服务中获取价值
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的更好方法?
答案 0 :(得分:0)
您需要在then
回调函数
categoryService.getCatId(sename).then(function (Id) {
$scope.categoryId=Id;
console.log($scope.categoryId)
});