Angular5 with Firebase, MySportsFeeds API, HttpClientModule

This is an example of a previous post showing new changes to Angular in the latest stable release.

Setting up FireBase.

  • Install these modules for firebase config. Run npm install angularfire2 firebase --save.
  • Import Firebase settings to app.module.ts.
  • Create a firebase db and config the db in app.module.ts.
  • In the firebase DB console click Authentication tab then click the WEB SETUP button top right. A modal pops up containing the config keys of the firebase DB.
  • Initialize app in the imports array in ngModule.
//app.module.ts

import { HttpClientModule } from "@angular/common/http";
import { FirebaseService } from './firebase.service';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';

export const firebaseConfig = {
  apiKey: ***,
  authDomain: ***,
  databaseURL: ***,
  storageBucket: ***
};

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    HttpClientModule,
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    AngularFireModule.initializeApp(firebaseConfig)
  ]
  providers: [FirebaseService],
})

Save Data to FireBase.

  • Create a firebase.service.ts with an addData function to call the firebase db.
  • Import the firebase.service into the app.component and call the addData function passing in the data to be save.
//firebase.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';

@Injectable()
export class FirebaseService {

  items: any;

  constructor(public af: AngularFireDatabase) {
    this.items = af.list('/data').valueChanges(); 
  }

  addData(stat) {
    this.af.list('/data').push(stat);
  }

  getData() {
    return this.items = this.af.list('/data').valueChanges();
  }
}

Get Data from FireBase.

  • Make a function called getData in the firebase.service file.
  • Call the getData function from app.component and save into an array to access it in the html.
//app.compoent.ts

import { Component, ViewChild, Inject, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { FirebaseService } from './firebase.service';
import { HttpClient, HttpResponse, HttpHeaders, HttpRequest} from '@angular/common/http'

let headers = new HttpHeaders().set("Authorization", "Basic " + btoa('username' + ":" + 'password'));
let url = 'https://api.mysportsfeeds.com/v1.1/pull/mlb/2017-regular/active_players.json?position=P';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

   playerData: Array<any>;
   showData: Array<any>;

   constructor(private firebaseService: FirebaseService, private http: HttpClient) {}
  
    loadData() {
      this.http.get(url, headers)
      .subscribe(res => {
        console.log(res['activeplayers'].playerentry, 'got active player data from api!');
        this.playerData = res['activeplayers'].playerentry;
      });

      for (let info of this.playerData) { 
         this.firebaseService
           .addData(info.player);
      }
      
      this.loadOtherData();

   }

   loadOtherData() {
    this.firebaseService
      .getData()
        .subscribe(firebaseData => {
        console.log(firebaseData, 'got response from firebase...');
        this.showData = firebaseData;
      });
   }
    
   ngOnInit() {
    this.loadData();
   }

}
//app.compoent.html

<ul>
  <li *ngFor="let data of showData"> 
    {{ data.player.FirstName + ' ' + data.player.LastName + ' - ' + data.team.Abbreviation }}
  </li>
</ul>

The main differences is that angularfire2 no longer uses FirebaseListObservable. To get data from firebase concat valueCahnges() to the angularfire list, af.list('/data').valueChanges() The HttpClientModule no longer uses the map operator to process json data. Also HttpHeaders replaces the old way Headers and RequestOptions were used in Angular previous to version 5

To compare differences see this original post of the same example using Angular4. Angular4 with Firebase: MySportsFeeds API Part 3, posted: October, 9, 2017.