使用 AngularFire2 将文件上传到 Firebase 存储
2017-08-21
1743
我正在使用 Angular2 和 Firebase 开展一个项目,我愿意将图像上传到 Firebase Storage。
因此,我使用构造函数和函数创建了组件,然后创建了模板。我不确定我声明变量 firebaseApp 的方式
public firebaseApp: FirebaseApp;
是否正确。
因此,在我的组件中,我有:
import { Component, OnInit, Inject, Input } from '@angular/core';
import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA, MdButton } from '@angular/material';
import { Http, Headers, Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import { FormBuilder, FormGroup } from '@angular/forms';
import { FirebaseApp } from 'angularfire2';
import 'firebase/storage';
@Component({
selector: 'individual-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class IndividualChat implements OnInit {
public firebaseApp: FirebaseApp;
constructor(
firebaseApp: FirebaseApp,
public afAuth: AngularFireAuth,
public af: AngularFireDatabase,
public http: Http,
public dialog: MdDialog
){ }
EditChatData(){
this.af.object('groupConversations/'+ this.my_id + '/' +this.conversation_id ).update({ groupName: this.group_edit_data.name ? this.group_edit_data.name : 'New Group' });
}
onChange(files) {
console.log(files, files[0]);
let storageRef = this.firebaseApp.storage().ref().child('groupImages');
storageRef.put(files[0]).then( snapshot => {
console.log('successfully added');
}).catch(err => { console.error("Whoupsss!", err) })
}
...
}
并且我在模板中创建的表单如下所示:
<form name="form" (ngSubmit)="EditChatData()" enctype="multipart/form-data">
<input type="file" #file (change)="onChange(file.files)" />
<input type="text" placeholder="Group name" name="name" [(ngModel)]="group_edit_data.name" #name="ngModel" class="form-control" value=" {{ group_name }}" />
<button class="btn">DONE</button>
</form>
我一直收到此错误:
ERROR TypeError: Cannot read property 'storage' of undefined
并且,我的 onChange(files) 中的 console.log 返回此对象:
FileList {0: File, length: 1}
length: 1,
0: File {
lastModified: 1503324156295
lastModifiedDate: Mon Aug 21 2017 17:02:36 GMT+0300 (EEST),
name:"Screenshot from 2017-08-21 17-02-36.png",
size: 401442,
type: "image/png",
webkitRelativePath: ""
}
2个回答
无法读取未定义的属性“存储”
告诉您
this.firebaseApp
为
未定义
。
您可以在构造函数中初始化它,方式如下:
constructor(
firebaseApp: FirebaseApp,
public afAuth: AngularFireAuth,
public af: AngularFireDatabase,
public http: Http,
public dialog: MdDialog
) {
this.firebaseApp = firebaseApp;
}
Ionică Bizău
2017-08-21
由于 FirebaseApp 是一项服务,因此您需要在构造函数中注入它。只有变量必须在构造函数上方声明。请确保导入 FirebaseApp。
Sai Prasad
2018-05-06