Samantha J Samantha J - 5 months ago 9
AngularJS Question

Why am I losing my object reference when I pass from a .forEach?

I have a question about passing by reference. In particular I am passing

wf
to wordFormUpdateSubmit.


  • When I do this:
    wf = response.data;
    it does not change anything in word.wordForms

  • When I do this:
    self.word.wordForms[key] = response.data;
    it correctly changes the contents of wf in word.wordForms



My question is why is it not passing by reference and why does
wf = response.data;
not work?

wordFormCheckAndUpdate = (): ng.IPromise<any> => {
var self = this;
var promises = [];
angular.forEach(self.word.wordForms, function (wf, key) {
var updatePromise = self.wordFormUpdateSubmit(wf, key);
promises.push(updatePromise);
});
return self.$q.all(promises);
};

wordFormUpdateSubmit = (wf: IWordForm, key: number): ng.IPromise<any> => {
var self = this;
return self.$http({
url: self.ac.dataServer + "/api/WordForm/Put",
method: "PUT",
data: wf
})
.then(
(any => {
// This does not correctly populate self.word.wordForms[0]
wf = response.data;

// This works
self.word.wordForms[key] = response.data;


});
}

Answer

JavaScript does not have pass-by-reference, it has "call by sharing".

If you assign a new value to a function parameter, it will not make any change to the original value passed into the function. It will just overwrite the parameter.

This should be a viable (and cleaner) alternative for what you are trying to do:

wordFormCheckAndUpdate = (): ng.IPromise<any> => {
    var self = this;

    return self.$q.all(self.word.wordForms.map((wf, key) =>
        self.wordFormUpdateSubmit(wf, key)
    ))
    .then(function (values) {
        self.word.wordForms = values;
    });
};

wordFormUpdateSubmit = (wf: IWordForm, key: number): ng.IPromise<any> => {
    var self = this;
    return self.$http({
        url: self.ac.dataServer + "/api/WordForm/Put",
        method: "PUT",
        data: wf
    })
    .then(response => response.data);
}