javascript - 上传图片,无法读取未定义的属性“订阅”
问题描述
我有一个简单的创建帖子功能,我想在填写标题、内容和图像时创建一个帖子:
但是当我上传图片时,进度条会填满,图片会上传到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);
}
}
解决方案
就像错误所说的那样,this.downloadURL
未定义,请确保在使用之前对其进行初始化
推荐阅读
- java - 由于 java.util.concurrent.TimeoutException,Eclipse 2020-06 不断冻结
- git - Git,删除我现在不需要推送的本地提交
- django - 在身份验证类中的 Django REST 框架中向请求添加数据
- javascript - 如何使用道具和反应钩子将来自后端的json数组传递给子组件?
- spring - 如何使用 spring data jpa 处理缓存实体的更新?
- swiftui - didSelect 上的 MapKit/MKMapViewDelegate:如果启用了用户位置,则底部工作表不会打开
- javascript - 粘贴或删除某些内容后,如何从 DOM 中取出元素?
- r - 如何在 R 中的两个 tiff 文件之间找到 r2 (Rsquared)?
- java - 在 Beam 中实现 GCS Blob 获取
- xml - ODT XML 文件的 XSL 更改结构