我在项目中显示图像时遇到问题。我想在 .subscribe 任务中将下载网址视为图像。所以它可以显示它。但是,当我这样做时,它会显示一条错误消息:
类型'UploadTaskSnapshot'不能指定为'string'类型。
以下是代码:
export class PostDashboardComponent implements OnInit {
title: string;
image: string = null;
content: string;
buttonText: string = "Create Post";
uploadPercent: Observable<number>;
downloadURL: Observable<string>;
constructor(
private auth: AuthService,
private postService: PostService,
private storage: AngularFireStorage
) { }
ngOnInit() {
}
uploadImage(event) {
const file = event.target.files[0]
const path = `posts/${file.name}`
const fileRef = this.storage.ref(path);
if (file.type.split('/')[0] !== 'image') {
return alert('only image files')
} else {
const task = this.storage.upload(path, file)
this.uploadPercent = task.percentageChanges();
task.snapshotChanges().pipe(
finalize(() => this.downloadURL = fileRef.getDownloadURL() )
)
.subscribe(url =&gt;(this.image = url))
console.log('Image Uploaded!');
我应该改变什么才能让它发挥作用,因为我是一个业余爱好者。谢谢你的帮助。
答案 0 :(得分:1)
我找到了答案,就是这样:
uploadImage(event) {
const file = event.target.files[0]
const path = `posts/${file.name}`
const fileRef = this.storage.ref(path);
if (file.type.split('/')[0] !== 'image') {
return alert('only image files')
} else {
const task = this.storage.upload(path, file);
const ref = this.storage.ref(path);
this.uploadPercent = task.percentageChanges();
console.log('Image uploaded!');
task.snapshotChanges().pipe(
finalize(() => {
this.downloadURL = ref.getDownloadURL()
this.downloadURL.subscribe(url => (this.image = url));
})
)
.subscribe();