【发布时间】: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 模板中。我是否以某种方式错误地绑定了变量?
【问题讨论】:
-
你为什么使用原始的
XMLHttpRequest是不可观察的并且不使用角度http? -
我关注 devcenter.heroku.com/articles/s3-upload-node - 但我想这就是原因,谢谢
标签: angular data-binding