我正在使用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: ""
}

最佳答案

Cannot read property 'storage' of undefined告诉您this.firebaseAppundefined

您可以通过以下方式在构造函数中对其进行初始化:

constructor(
  firebaseApp: FirebaseApp,
  public afAuth: AngularFireAuth,
  public af: AngularFireDatabase,
  public http: Http,
  public dialog: MdDialog
) {
  this.firebaseApp = firebaseApp;
}

10-07 19:11
查看更多