Angular2 view not updated after callback function

105 views Asked by At

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";

            }
        });
    }

}
2

There are 2 answers

3
Günter Zöchbauer On BEST 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

0
roish On

this one is working for me: (narrow function+Ngzone)

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


        }
    });