我正在使用Angular2和Firebase开展项目,我愿意将图片上传到Firebase存储。
因此,我使用构造函数和函数创建了Component,然后创建了模板。我不确定我声明变量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(文件)中的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: ""
}
答案 0 :(得分:4)
Cannot read property 'storage' of undefined
告诉您this.firebaseApp
是undefined
。
您可以在构造函数中初始化它,这样:
constructor(
firebaseApp: FirebaseApp,
public afAuth: AngularFireAuth,
public af: AngularFireDatabase,
public http: Http,
public dialog: MdDialog
) {
this.firebaseApp = firebaseApp;
}
答案 1 :(得分:1)
由于FirebaseApp是一个服务,您需要在构造函数中注入。只有变量必须在构造函数上面声明。确保导入FirebaseApp。