簡體   English   中英

Angular2變量更改后未更新

[英]Angular2 variable not updating after change

我正在嘗試構建一個組件,用戶在其中輸入圖像,然后將其上載到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有一個用於XmlHttpRequest的包裝,稱為BrowserXhr,您應該在angular中使用Http服務。 即:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM