Reputation: 3787
Fairly new to Angular...
So If I'm using Ajax (rather than $http) in an Angular service, I want to keep a reference to a callback function. I suspect that there may be a race condition here with the this.callback
variable.
Can another session come in and stomp on this.callback
while the first session is still doing the Ajax call?
var myServer = angular.module("mymod", ["my.server"]);
myServer.service("$myservice",
function($server)
{
var me = this;
this.callback = null;
this.saveDone = function(data)
{
if (me.callback) me.callback();
}
this.save = function(item, cb)
{
me.callback = cb;
dict = {"name" : "savePDataStory"};
dict.item = item;
actions = [dict];
$server.realAjaxCall(actions, this.saveDone, true);
}
Upvotes: 0
Views: 88
Reputation: 26
Yes. Each call to save
will overwrite this.callback
since it is shared across calls to save
. A solution is to store the callback inside save
itself which will be unique per invocation of the function. You can do this inline like so:
$server.realAjaxCall(actions, function (data) {
cb();
}, true);
This preserves the behavior of the original code snippet which doesn't include data
when callback
is called. If you don't mind passing data
through to callback
, you can simplify it by using cb
directly instead of wrapping it inside a function:
$server.realAjaxCall(actions, cb, true);
Upvotes: 1