首页 > 解决方案 > 上传图片,无法读取未定义的属性“订阅”

问题描述

我有一个简单的创建帖子功能,我想在填写标题、内容和图像时创建一个帖子:

在此处输入图像描述

但是当我上传图片时,进度条会填满,图片会上传到firebase,但它不允许我创建帖子,当我在控制台中对其进行测试时,它会出现以下错误:

在此处输入图像描述

这是代码:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../core/auth.service';
import { AngularFireStorage } from 'angularfire2/storage';



import { PostService } from '../post.service';
import { Observable } from 'rxjs/Observable';



@Component({
  selector: 'app-post-dashboard',
  templateUrl: './post-dashboard.component.html',
  styleUrls: ['./post-dashboard.component.css']
})
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}`
    if (file.type.split('/')[0] !== 'image') {
      return alert('only image files')
    } else {
      const task = this.storage.upload(path, file)
      this.uploadPercent = task.percentageChanges()
      console.log('Image Uploaded!')
      this.downloadURL.subscribe(url => this.image = url)
    }
  }

  createPost() {
    const data = {
      author: this.auth.authState.displayName || this.auth.authState.email,
      authorId: this.auth.currentUserId,
      content: this.content,
      image: this.image,
      published: new Date(),
      title: this.title
    };
    this.postService.create(data)
    this.title = ''
    this.content = ''
    this.image = ''
    this.buttonText = 'Post Created!'
    setTimeout(() => (this.buttonText = "Create Post"), 3000);
  }
}

标签: javascriptangular

解决方案


就像错误所说的那样,this.downloadURL未定义,请确保在使用之前对其进行初始化


推荐阅读