首页 > 解决方案 > 上传任务快照问题

问题描述

我在项目中显示图像时遇到问题。我希望在.subscribe任务中下载 url 与图像相同。所以它可以显示它。但是当我这样做时,它会显示一条错误消息:

类型“UploadTaskSnapshot”不可分配给类型“字符串”。

这是代码:

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 => (this.image = url))

      console.log('Image Uploaded!');

因为我是一个业余爱好者,我应该改变什么才能让它工作。谢谢您的帮助。

标签: angularjstypescriptfirebasefirebase-storage

解决方案


我找到了答案,是这样的:

  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();

推荐阅读