【问题标题】:Angular2 variable not updating after changeAngular2变量在更改后不更新
【发布时间】:2018-01-05 02:57:59
【问题描述】:

我正在尝试构建一个组件,用户在其中输入图像,然后将其上传到 s3,然后显示该图像的 url。我有以下html模板

{{imgUrls}}
<div>
      <input type="file" (change)="testOnChange($event)"/>
</div>

连接到包含以下打字稿代码的组件

    public imgUrls = [];

    testOnChange(event){
        var files = event.srcElement.files;
        this.getSignedRequest(files[0]);
    }

    uploadFile(file, signedRequest, url){
        console.log("inside uploadFile()");

        const xhr = new XMLHttpRequest();
        xhr.open('PUT', signedRequest);
        xhr.onreadystatechange = () => {
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    this.imgUrls.push(url);
                    console.log(this.imgUrls);
                }
                else{
                    alert('Could not upload file.');
                }
            }
        };
        xhr.send(file);
    }

    getSignedRequest(file){
        console.log("inside getSignedRequest()");
        const xhr = new XMLHttpRequest();
        xhr.open('GET', `http://localhost:3000/job/sign-s3?file-name=${file.name}&file-type=${file.type}`);
        xhr.onreadystatechange = () => {
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    const response = JSON.parse(xhr.responseText);
                    this.uploadFile(file, response.signedRequest, response.url);
                }
                else{
                    alert('Could not get signed URL.');
                }
            }
        };
        xhr.send();
    }

uploadFile() 中的日志语句确实显示了包含正确 url 的更新后的 imgUrls 变量 - 但是 {{imgUrls}} 在 html 模板中实际上从未更改。我不确定为什么日志语句显示 imgUrls 已更改,但更改从未反映在实际的 html 模板中。我是否以某种方式错误地绑定了变量?

【问题讨论】:

标签: angular data-binding


【解决方案1】:

Angular 有一个名为 BrowserXhr 的 XmlHttpRequest 包装器,您应该在 Angular 中使用 Http 服务。即:

constructor(private _http: Http){  
    _http.get(url); // etc
}

【讨论】:

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