Petko Kamenov
Petko Kamenov

Reputation: 2426

Get data from Firebase after is initialized

I want to get data from db from my main component only after I am connected to Firebase

this.AngularFireModule.initializeApp(environment.firebase)

This is in my app.module. I want to get data from db after Firebase is initialized. The problem is that I try to get my user data from db but I get error first time I tried because my app is not connected to firebase. When I refresh the page there is no problem because is already connected.

Here is my app.module.ts

 @NgModule({
declarations: [
AppComponent,
HomeComponent,
CategorieComponent,
SignComponent,
TopicComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(appRoutes),
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule, // imports firebase/database, only needed 
for database features
AngularFireAuthModule // imports firebase/auth, only needed for auth 
features
],
providers: [SharedService, UsersService],
bootstrap: [AppComponent]
})
export class AppModule { }

Upvotes: 0

Views: 519

Answers (1)

Markus Kollers
Markus Kollers

Reputation: 3718

-- EDIT --
It's not a Firebase issue, it's a timing problem. After starting your app, Firebase has to read and decrypt the user-token from the localstorage. Until this has finished, currentUser is undefined and you will get an error if you try to access properties like email or uid.

I recommend you to use Observables, to track changes. Otherwise you will receive the same problems on login and logout. This can look like the following:

userService.ts

...
public authInfo = new BehaviorSubject<UserInfo>(undefined);
authInfo$ = this.authInfo.asObservable();

constructor(private fbAuth: AngularFireAuth) {
   this.fbAuth.auth.onAuthStateChanged(authInfo => this.authInfo.next(authInfo));
}
...

component.ts

...
authInfo$: Observable<UserInfo>;

constructor(private userService: UserService) {
   this.authInfo$ = this.authService.authInfo$;
}
...

component.html

...
<div>{{ (authInfo$ | async)?.email }}</div>
...

The async-pipe manages the subscription of the observable, and the elvis-operator (?) checks for null and undefined.

Upvotes: 1

Related Questions