Accessing firebase.storage() with AngularFire2 (Angular2 rc.5)

天大地大妈咪最大 提交于 2019-11-27 10:53:31

Internally, AngularFire2 calls Firebase's initializeApp in a DI factory when creating its FirebaseApp.

You are seeing the error because you are accessing the global firebase instance and initializeApp has not yet been called - as the DI infrastructure has not needed to create FirebaseApp or any of its dependencies.

Rather than using the global firebase, you could inject FirebaseApp (which is the value returned by Firebase's initializeApp function):

import { Component, Inject } from '@angular/core';
import { FirebaseApp } from 'angularfire2';

@Component({
  template: '<img [src]="image">'
})
export class RecipesComponent {
  image: string;
  constructor(@Inject(FirebaseApp) firebaseApp: any) {
    const storageRef = firebaseApp.storage().ref().child('images/image.png');
    storageRef.getDownloadURL().then(url => this.image = url);
  }
}

And, as it's no longer required, you could delete declare var firebase : any;.


Early versions of the Firebase NPM module did not include typings. Recent versions now include them, so the firebaseApp property could be strongly typed like this:

import { Component, Inject } from '@angular/core';
import { FirebaseApp } from 'angularfire2';
import * as firebase from 'firebase';

@Component({
  template: '<img [src]="image">'
})
export class RecipesComponent {
  image: string;
  constructor(@Inject(FirebaseApp) firebaseApp: firebase.app.App) {
    const storageRef = firebaseApp.storage().ref().child('images/image.png');
    storageRef.getDownloadURL().then(url => this.image = url);
  }
}

With the refactoring that accompanied the version 4 release candidate of AngularFire2, FirebaseApp is no longer a token, so the injection can be simplified:

import { Component, Inject } from '@angular/core';
import { FirebaseApp } from 'angularfire2';
import 'firebase/storage';

@Component({
  template: '<img [src]="image">'
})
export class RecipesComponent {
  image: string;
  constructor(firebaseApp: FirebaseApp) {
    const storageRef = firebaseApp.storage().ref().child('images/image.png');
    storageRef.getDownloadURL().then(url => this.image = url);
  }
}

However, an explicit import of firebase/storage is required because AngularFire2 now imports only the portions of the Firebase API that it uses. (Note that there is a proposal for storage support.)

William Wu

The above code no longer works, I keep getting 'firebase.storage is not a function', try adding the following code:

import * as firebase from 'firebase/app';
import 'firebase/storage';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!