上传图片,无法读取未定义

时间:2018-05-25 09:45:41

标签: javascript angular

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

enter image description here

但是当我上传图片时,进度条会填充,图片会上传到firebase,但它不会让我创建帖子,当我在控制台中测试它时会出现此错误:

enter image description here

以下是代码:

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

1 个答案:

答案 0 :(得分:1)

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