user2695221 user2695221 - 1 month ago 10
Javascript Question

Angular2 view not updated after callback function

I'm using Meteor-Angular2 and slingshot package for uploading images to S3 storage. when returning from the function and assign to binded string, view not updated. (setTimout function is working and updating view, but uploader function not)

export class AdminComponent {

public urlVariable: string = "ynet.co.il";

constructor() {
this.uploader = new Slingshot.Upload("myFileUploads");
setTimeout(() => {
this.urlVariable = "View is updated";
}, 10000);
}

onFileDrop(file: File): void {
console.log('Got file2');

this.uploader.send(file, function (error, downloadUrl) {
if (error) {
// Log service detailed response
}
else {

this.urlVariable = "View not updated";

}
});
}

}

Answer

Use arrow functions (() =>) instead of function () to retain the scope of this.

    this.uploader.send(file, (error, downloadUrl) => {
        if (error) {
            // Log service detailed response
        }
        else {
            // now `this.` points to the current class instance
            this.urlVariable = "View not updated";

        }
    });

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions