I am trying to access firebase.storage() on my project, with:
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.)
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';