Reputation: 18443
I have some controller and a function called to obtain some value from a REST WCF web service:
fooBar.controller('fooCtrl',
function fooCtrl($scope, $http, $resource) {
$scope.someOnClickEvent = function () {
GetSomething('a','b','c');
}
}
);
function GetSomething($scope, $resource, a, b, c) {
var ServiceHandle = $resource('some/addr');
var serviceHandle = new ServiceHandle();
serviceHandle.a = a;
serviceHandle.b = b;
serviceHandle.c = c;
serviceHandle.$save().then(function (result) {
console.log('So response should be ready');
$scope.result = result.ValueFromService;
});
}
As far as I know $save()
returns promise and function inside .then
should be called right after response is returned by the server. In my case it's called imediately.
If service returns true I'm going to show some popup, so I need this value to be returned before conditional instruction is executed.
Version of Angular is 1.4.9.
Upvotes: 1
Views: 496
Reputation: 18443
I've analysed code and its behavior and I'm wrong obviously. Maybe I should delete this question, but I believe it can help someone to understand similar problems.
Function inside .then
is in fact called after a response comes from the server. It can be verified using for instance Chrome's developer tools (namely tab network).
However if just after calling GetSomething function we want to access a $scope.result
we are making a great mistake. $scope.result
will be undefined
as long as function inside .then
won't be executed. To use a value returned from a service we must do it inside .then
function or in a function called by it.
Upvotes: 2