Angular2视图在回调函数后没有更新

时间:2016-10-20 05:47:48

标签: javascript meteor angular meteor-slingshot

我使用Meteor-Angular2和弹弓包将图像上传到S3存储。从函数返回并分配给绑定字符串时,视图未更新。 (setTimout函数正在工作并更新视图,但上传器功能没有)

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 个答案:

答案 0 :(得分:1)

使用箭头功能(() =>)代替function ()来保留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

答案 1 :(得分:0)

这个对我有用:(缩小功能+ 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"; });


        }
    });