Angular4 with Firebase: MySportsFeeds API Part 3

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.
  • Initialize app in the imports array in ngModule.
//app.module.ts

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: [
    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, FirebaseListObservable } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';

@Injectable()
export class FirebaseService {

  items:FirebaseListObservable<any[]>;

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

  addData(stat) {
    this.items.push(stat);
  }

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

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 { Http, Response, RequestOptions, Headers, Request, RequestMethod } from '@angular/http';
import 'rxjs/add/operator/map';

let headers = new Headers({ "Authorization": "Basic " + btoa('username' + ":" + 'password') });
let options = new RequestOptions({ headers: headers });
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: Http) {}
  
    loadData() {
      this.http.get(url, options)
     .map(response => response.json())
      .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>
  • Above is a very basic way to save and get data from firebase. Normally this wouldn’t be a way to use firebase if you already have data coming in from the api. In this app I use firebase to store a week’s worth of game data in firebase to avoid having to call the api 70 times to get the data when the app loads. This is a reason to use firebase, to store large amounts of data. See below for example of making several api calls dynamically.

Check the codebase on my GitHub account!