Search code examples
angularangularfire2angular2-router

How Can I Subscribe To Firebase data using AngularFire2 on initial route load?


I'm using angular-cli to build an angularfire2 application.

I'm having an issue where upon initial child sub route load, angularfire2 throws an error in the console:

error_handler.js:47 EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of undefined

This happens when my page "refreshes". If I navigate away from the component and back to it after a refresh, the data loads just fine and I don't receive the error. I'm not sure if this is a bug with Angular2, AngularFire2, or if I'm doing something wrong. Has anyone had this problem? Here is my relevant component code:

import {Component, OnInit, ViewChild, OnDestroy}from '@angular/core';
import {Router} from '@angular/router';
import {AngularFire, FirebaseListObservable, AngularFireModule} from 'angularfire2';


@Component({
  selector: 'app-users',
  templateUrl: 'users.component.html',
  styleUrls: ['users.component.scss', '../shared/styles/dashboard.scss']
})
export class EmployeesComponent implements OnInit, OnDestroy {
  private groupKey: string;
  private groupAdmin: string;
  private user: any;
  private _auth: any;

  private positions: FirebaseListObservable < any > ;
  private users: FirebaseListObservable < any > ;

  constructor(private af: AngularFire, private router: Router) {}

  ngOnInit() {
    this.af.auth.subscribe(auth => {
      this._auth = auth;
      let currentUser = this.af.database.object('/Users/' + this._auth.uid).take(1).subscribe(user => {
        this.groupKey = user.group;
        this.users = this.af.database.list('/Users', {
          query: {
            orderByChild: 'group',
            equalTo: this.groupKey
          }
        });
        this.positions = this.af.database.list('/Groups/' + this.groupKey + '/Positions');
        this.af.database.object('/Groups/' + this.groupKey + '/admin').take(1).subscribe(group => {
          this.groupAdmin = group.admin;
        });
      });
    });
  }



  ngOnDestroy() {
    this.users.subscribe().unsubscribe();
    this.positions.subscribe().unsubscribe();
  }

}


Solution

  • You must refactory your ngOnDestroy method, because it is wrong, first if you are using async pipe inside your template you don't need to unsubscribe and if you don't, inside your ngOnInit you should save a reference to unsubscribe function for each subscription call and then call them on ngOnDestroy(you can read more about it here).