我试图在uploadTask成功后显示上传的img,但是由于异步加载,视图会在上传完成之前尝试显示它。
这是方法:
upload(value){
let file = value.target.files[0];
let storageRef = firebase.storage().ref('noticias/' + file.name);
let uploadTask = storageRef.put(file);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
function(snapshot) {
let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
switch (error) {
case 'storage/unauthorized':
break;
case 'storage/canceled':
break;
case 'storage/unknown':
break;
}
}, function() {
// Upload completed successfully, now we can get the download URL
let downloadURL = uploadTask.snapshot.downloadURL;
console.log('Upload done!');
});
storageRef.getDownloadURL().then(url => this.imgUrl = url);
this.uploadedImg = true;
}
这就是观点:
<img *ngIf="uploadedImg" [src]="imgUrl" />
该方法的最后两行是过早加载的方法。我也尝试将它们移到成功函数中。问题是,如果我在那里移动它们,this
不再引用该类,我无法更改视图中的值。
答案 0 :(得分:0)
失去对this
的引用是javascript中的常见问题,并且有一个简单的模式来跟踪它。你在成功函数中移动线条是正确的,只需在开始时执行此操作:
upload(value){
let that = this;
let file = value.target.files[0];
现在that
将始终指向原始this
,以下内容将按预期运行:
}, function() {
// Upload completed successfully, now we can get the download URL
let downloadURL = uploadTask.snapshot.downloadURL;
console.log('Upload done!');
// Using original `this`
storageRef.getDownloadURL().then(url => that.imgUrl = url);
that.uploadedImg = true;
});