Search code examples
angularfirebaserxjscombinelatest

How to deal with all the Observables when building an Angular App that uses Firebase


I've built a few apps with Angular and Firebase and I'm just starting a new one. I'm interested in how others deal with getting data using observables. In my specific app I need to use an observable to get the parameters from the URL, check if the user is authenticated, and get 2 different objects from firebase. I need to first check auth, then get parameters from the URL so I can find the locations of the firebase objects. In the past I've just done a nest of observable subscriptions like this.

ngOnInit() {
    this.af.auth.subscribe(auth => {
      if (auth) {
        this.uid = auth.uid;
        this.af.database.list('objectives', {
          query: {
            orderByChild: 'AuthorID',
            equalTo: auth.uid
          }
        }).subscribe(objectives => {
          console.log(objectives);
          this.allObjectives = objectives;
        })
      } else {
        this.router.navigate(['login'])
      }
    })
  }

Now I have to add the parameters and another call to firebase. I've tried using rxjs's combineLatest but it doesn't look like I can use data returned from one observable to use in another. My question is, has anyone solved a similar issue without nesting subscriptions?

Below is my package.json file

{
  "name": "wdw-hunt",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/router": "^3.4.0",
    "angular2-cookie": "^1.2.6",
    "angularfire2": "^2.0.0-beta.8",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "firebase": "^3.9.0",
    "hammer-timejs": "^1.1.0",
    "hammerjs": "^2.0.8",
    "ng2-bootstrap": "^1.4.2",
    "ng2-simple-page-scroll": "^2.0.0",
    "rxjs": "^5.1.0",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0-rc.2",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "firebase-cli": "^1.2.0",
    "firebase-tools": "^3.5.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "^2.3.2"
  }
}

Below is my tsconfig

{
  "compilerOptions": {
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "lib": [
      "es2016",
      "dom"
    ],
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Solution

  • This is how I do it

    Guard:

    import {Injectable} from '@angular/core';
    import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
    import {Observable} from 'rxjs/Observable';
    import {AngularFire} from 'angularfire2';
    import {isNullOrUndefined} from 'util';
    
    @Injectable()
    export class OverviewGuard implements CanActivate {
      constructor(private af: AngularFire, private router: Router) {
    
      }
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
        return this.af.auth.map(auth => {
          if (isNullOrUndefined(auth)) {
            this.router.navigate(['/login']);
            return false;
          } else {
            return true;
          }
        });
      }
    }
    

    Some provider:

    import {Injectable} from '@angular/core';
    import {AngularFire} from 'angularfire2';
    import {Observable} from 'rxjs/Observable';
    
      @Injectable()
      export class JobProvider {
        constructor(private af: AngularFire) {
        }
    
        public getSomething(): Observable<Something> {
          return this.getUserDb()
            .switchMap(path => this.af.database.object(`${path}/something`));
        }
    
        private getUserDb(): Observable<string> {
          return this.af.auth
            .map(auth => `/debug/users/${auth.uid}`);
        }
    
      }