【问题标题】:Angular2 view not updated after callback function回调函数后Angular2视图未更新
【发布时间】:2017-03-01 23:30:02
【问题描述】:

我正在使用 Meteor-Angular2 和 slingshot 包将图像上传到 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";

            }
        });
    }

}

【问题讨论】:

    标签: javascript meteor angular meteor-slingshot


    【解决方案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

    【讨论】:

    • 仍然没有更新视图,除非我移动到路由器中的另一条路由或执行一些触发刷新页面的操作。
    • 从哪里调用onFileDrop
    • 谢谢!加上你的回答和补充 this._ngZone.run(() => {this.urlVariable = "View not updated"; });它现在正在工作并立即更新! :-)
    【解决方案2】:

    这个对我有用:(窄函数+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"; });
    
    
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      • 2016-12-21
      • 2023-03-17
      相关资源
      最近更新 更多