SlideShare una empresa de Scribd logo
1 de 53
Angular 4
with Firebase
FAST TRACK YOUR DEV
Annie Bougie
Senior Developer, Concurrency, Inc
@bougiefever
anne.bougie@gmail.com
Why is Developing a New Site So Hard?
• Build a UI
• Make it Responsive
• Build an API
• Data Modeling
• Authentication
• Security
• Hosting
• Notifications
• How much will it cost?
Angular + Firebase
Starting A New App?
Angular 4 Is A Good Choice
◦Modularized components are maintainable
◦Cross platform support
◦GoodTooling
◦Large Dev Community
What About Everything Else?
◦ REST Api
◦ Hosting
◦ Automatic Scaling
◦ Authentication
◦ File Storage
◦ SSL
◦ Analytics
◦ Cloud Messaging
Realtime NoSQL Database
◦ All clients subscribe to one database
instance
◦ Interact asynchronously with RxJs
Observables
Set Up
Firebase
FIREBASE CONSOLE
https://console.firebase.google.com
Database
Authorization
Firebase (NoSQL) Data Modeling
Avoid deeply nested hierarchies
Use association tables to link records
-| events
-| instructors
-| scheduledEvents
-| eventInstructorLink
-| eventKey
-| instructorKey (1 or more)
-| instructorEventLink
-| instructorKey
-| eventKey (1 or more)
-| comments
-| scheduledEventId
Set Up
Angular
ANGULAR-CLI
Setting up Angular for Firebase
PREREQUISITES
Node.js 6.9.0 or higher
Npm 3 or higher
RECOMMENDED SOFTWARE
VSCode, WebStorm, Sublime
Yarn
Download and install node from nodejs.org
npm install –g @angular/cli
npm install –g typescript
npm install –g typings
ng new <project-name>
npm install firebase, angularfire2 --save
AngularFire2
Observable based - Use the power of RxJS, Angular, and Firebase.
Realtime bindings - Synchronize data in reatime.
Authentication - Log users in with a variety of providers and
monitor authentication state in realtime.
firebase SDK
◦ For when you need more functionality than what AngularFire2 offers
◦ Not an NgModule
Copy config values into src/environments/environment.ts in Angular App
Add Firebase Config
export const environment = {
production: false,
firebaseConfig: {
apiKey: "AIzaSyCbVRqtVxNZBb6b0ie34wJdC3OjBHSA5DE",
authDomain: "fir-demo-1238d.firebaseapp.com",
databaseURL: "https://fir-demo-1238d.firebaseio.com",
projectId: "fir-demo-1238d",
storageBucket: "fir-demo-1238d.appspot.com",
messagingSenderId: "398640249561"
}
};
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from ‘angularfire2/database’;
import { environment } from '../environments/environment’;
/// omit code ///
@NgModule({
imports: [
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFireDatabaseModule,
AngularFireAuthModule,
/// omit code ///
export class AppModule { }
Root Angular Module
Save and
Retrieve Data
ANGULAR FIRE DATABASE
& ANGULAR FIRE APP
Retrieving Firebase Data
◦ Get a reference to the node
◦ Add any query or limits to the data you want to retrieve
◦ Subscribe to the data
Getting Firebase Objects
The Code
constructor(private db: AngularFireDatabase) {
const pathToObject = '/events/1’;
this.event$ = this.db.object(pathToObject);
}
The HTML
<p>
{{ (event$ | async)?.name }}
</p>
Getting Firebase Lists
The Code
The HTML
constructor(private db: AngularFireDatabase) {
this.events$ = db.list("events");
}
<ul>
<li *ngFor="let event of (events$ | async)">{{event.name}}</li>
</ul>
Saving to Firebase
◦ Push to list – Firebase determines the key
◦ Update an object – Only updates properties you specify
◦ Set an object – Replaces the object
◦ Atomic saves using the firebaseSDK
◦ REST
Updating Objects in Firebase
REPLACING OBJECTS WITH SET UPDATING OBJECTS WITH UPDATE
this.db.object(this.pathToObject)
.set(event);
this.db.object(this.pathToObject)
.update(
{like: 'someone likes this’}
);
Pushing To A Firebase List
events$: FirebaseListObservable<any>;
constructor(private db: AngularFireDatabase) {
this.events$ = db.list("events");
}
addEvent(name) {
this.events$.push({name: name});
}
Firebase Push Keys
◦ Encoded time stamp
◦ Unique ID
◦ Accessed with the $key attribute
Atomic Saves with the Firebase SDK
constructor(
private db: AngularFireDatabase,
@Inject(FirebaseApp) firebaseApp: FirebaseApp) {
this.database = firebaseApp.database();
}
like() {
let likesRef = this.database.ref('likes’);
let likePushKey = likesRef.push().key;
/// omitted ///
let saveObjects = {};
saveObjects[`events/${eventKey}`] = likedEvent;
saveObjects[`likes/${likePushKey}/${eventKey}`] = true;
this.database.ref().update(saveObjects);
}
Firebase
Hosting
Quick Hosting in Firebase
npm install –g firebase-tools
firebase login
firebase init
firebase deploy
Firebase
Queue
NODE APP
Firebase Queue
Node app
Listens on a queue and processes each message that arrives
Firebase Auth
& Auth
ANONYMOUS, EMAIL & PASSWORD,
SOCIAL
Firebase
Authentication
◦ You must enable the types of
authentication you want to
use.
◦ Social authentication requires
further set up
Add Firebase Authentication to
Angular
import { AngularFireAuthModule } from "angularfire2/auth";
imports: [
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFireDatabaseModule,
AngularFireAuthModule,
Track Authentication State
constructor(
private angularFireAuth: AngularFireAuth,
private snackbar: MdSnackBar
) {
this.angularFireAuth.authState.subscribe(auth => this.authState = auth);
}
get authenticated(): boolean {
return this.authState !== null;
}
get currentUser(): any {
return this.authenticated ? this.authState : null;
}
Login
anonymousLogin() {
return this.angularFireAuth.auth.signInAnonymously()
.then((user) => {
this.authState = user;
})
.catch(error => console.log(error));
}
googleSignIn() {
const provider = new firebase.auth.GoogleAuthProvider()
return this.angularFireAuth.auth.signInWithPopup(provider)
.then((credential) => this.authState = credential.user)
.catch(error => console.log(error));
}
Logout
logout() {
this.angularFireAuth.auth.signOut()
.then(() => this.authState = null)
.catch(error => console.log(error));;
}
Firebase Push
Notifications
BROWSER SERVICE WORKER WITH CLOUD
SERVICES
Firebase Push Notifications
Set up Angular App For Messaging
Add manifest.json
Add firebase-messaging-sw.js
Save messaging token
Receive messages
manifest.json
{
"short_name": "LibraryEvents",
"name": "Event Tracker for Libraries",
"gcm_sender_id": "103953800507"
}
firebase-messaging-sw.js
Copy messaging id from firebase config
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
var config = {
messagingSenderId: "346952864544"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
Set up Angular
import { AngularFireAuth } from 'angularfire2/auth';
import { FirebaseApp } from 'angularfire2';
import * as firebase from 'firebase’;
...
messaging = firebase.messaging();
...
this.messaging.requestPermission()
...
this.messaging.getToken();
...
this.messaging.onMessage((payload: any) => {
...
});
Firebase
Project
Server
Key
Send Notification Message
Cloud Function to Send Notifications
◦ Listen when a data event happens
◦ Send notification to users who have granted permission
◦ Cloud functions are Node apps
Generate firebaseadmin-sdk Key
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const dateformat = require('dateformat');
exports.notifyScheduledEventFunction = functions.database.ref('/scheduledEvents/{scheduledEventId}').onCreate(event =>
{
const libararyEvent = event.data.val();
const scheduledEventId = event.params.scheduledEventId;
const db = admin.database();
db.ref(`/scheduledEvents/${scheduledEventId}`).once('value', snapshot => {
let se = snapshot.val();
const payload = {
notification: {
title: se.eventName,
body: se.eventName + ' was scheduled on ' + dateformat(se.eventDate, 'mm/dd') + ' by ' + se.instructorName,
icon: "https://placeimg.com/250/250"
}
};
db.ref('/tokens').once('value').then(tokens => {
tokens.forEach(function(token) {
var data = token.val();
admin.messaging().sendToDevice(data.token, payload)
});
});
});
Resources
Annie Bougie @bougiefever
Demo code: https://github.com/Bougiefever/firebase-simple-demo
Firebase Queue Sample code: https://github.com/Bougiefever/library-events-likes
Library Events App: https://github.com/Bougiefever/library-events-manager
Firebase Blog: https://firebase.googleblog.com/
How To Firebase: https://howtofirebase.com/
Angular with Firebase Blog: https://angularfirebase.com/
Angular University: https://angular-university.io/
Egghead: Courses on both Angular and Firebase: https://egghead.io/

Más contenido relacionado

La actualidad más candente

Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
維佋 唐
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine
 
NSA for Enterprises Log Analysis Use Cases
NSA for Enterprises   Log Analysis Use Cases NSA for Enterprises   Log Analysis Use Cases
NSA for Enterprises Log Analysis Use Cases
WSO2
 

La actualidad más candente (20)

Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
 
Local Authentication par Pierre-Alban Toth
Local Authentication par Pierre-Alban TothLocal Authentication par Pierre-Alban Toth
Local Authentication par Pierre-Alban Toth
 
Making connected apps with BaaS (Droidcon Bangalore 2014)
Making connected apps with BaaS (Droidcon Bangalore 2014)Making connected apps with BaaS (Droidcon Bangalore 2014)
Making connected apps with BaaS (Droidcon Bangalore 2014)
 
APIs, APIs Everywhere!
APIs, APIs Everywhere!APIs, APIs Everywhere!
APIs, APIs Everywhere!
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the Things
 
Writing JavaScript Applications with the AWS SDK (TLS303) | AWS re:Invent 2013
Writing JavaScript Applications with the AWS SDK (TLS303) | AWS re:Invent 2013Writing JavaScript Applications with the AWS SDK (TLS303) | AWS re:Invent 2013
Writing JavaScript Applications with the AWS SDK (TLS303) | AWS re:Invent 2013
 
03 integrate webapisignalr
03 integrate webapisignalr03 integrate webapisignalr
03 integrate webapisignalr
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
NSA for Enterprises Log Analysis Use Cases
NSA for Enterprises   Log Analysis Use Cases NSA for Enterprises   Log Analysis Use Cases
NSA for Enterprises Log Analysis Use Cases
 
Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)
 
Micronaut: Changing the Micro Future
Micronaut: Changing the Micro FutureMicronaut: Changing the Micro Future
Micronaut: Changing the Micro Future
 
Vaadin and Spring at Devoxx UK 2015
Vaadin and Spring at Devoxx UK 2015Vaadin and Spring at Devoxx UK 2015
Vaadin and Spring at Devoxx UK 2015
 
Azure Durable Functions (2018-06-13)
Azure Durable Functions (2018-06-13)Azure Durable Functions (2018-06-13)
Azure Durable Functions (2018-06-13)
 
Cutting edge HTML5 API you can use today (by Bohdan Rusinka)
 Cutting edge HTML5 API you can use today (by Bohdan Rusinka) Cutting edge HTML5 API you can use today (by Bohdan Rusinka)
Cutting edge HTML5 API you can use today (by Bohdan Rusinka)
 
Leveraging parse.com for Speedy Development
Leveraging parse.com for Speedy DevelopmentLeveraging parse.com for Speedy Development
Leveraging parse.com for Speedy Development
 
Designing and Running a GraphQL API
Designing and Running a GraphQL APIDesigning and Running a GraphQL API
Designing and Running a GraphQL API
 
Web Api vs MVC
Web Api vs MVCWeb Api vs MVC
Web Api vs MVC
 
Grails Plugins
Grails PluginsGrails Plugins
Grails Plugins
 
Inside Azure Diagnostics
Inside Azure DiagnosticsInside Azure Diagnostics
Inside Azure Diagnostics
 

Similar a Angular 4 with firebase

Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914
LearningTech
 
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure FunctionsSharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
Sébastien Levert
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
Pedro Morais
 

Similar a Angular 4 with firebase (20)

Serverless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsServerless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applications
 
Introduction to Firebase on Android
Introduction to Firebase on AndroidIntroduction to Firebase on Android
Introduction to Firebase on Android
 
Firebase overview
Firebase overviewFirebase overview
Firebase overview
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Building an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and FirebaseBuilding an Android app with Jetpack Compose and Firebase
Building an Android app with Jetpack Compose and Firebase
 
Lecture 11 Firebase overview
Lecture 11 Firebase overviewLecture 11 Firebase overview
Lecture 11 Firebase overview
 
Chris O'Brien - Best bits of Azure for Office 365/SharePoint developers
Chris O'Brien - Best bits of Azure for Office 365/SharePoint developersChris O'Brien - Best bits of Azure for Office 365/SharePoint developers
Chris O'Brien - Best bits of Azure for Office 365/SharePoint developers
 
Full Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication SystemFull Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication System
 
Intro to Firebase || Event by DSC UNIDEB
Intro to Firebase || Event by DSC UNIDEBIntro to Firebase || Event by DSC UNIDEB
Intro to Firebase || Event by DSC UNIDEB
 
Angular JS2 Training Session #3
Angular JS2 Training Session #3Angular JS2 Training Session #3
Angular JS2 Training Session #3
 
Firestore MENA digital days : GDG Abu dhabi
Firestore MENA digital days : GDG Abu dhabiFirestore MENA digital days : GDG Abu dhabi
Firestore MENA digital days : GDG Abu dhabi
 
Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]
 
Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914
 
Quick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase ServerQuick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase Server
 
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure FunctionsSharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
 
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
 
Building with Firebase
Building with FirebaseBuilding with Firebase
Building with Firebase
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
 

Último

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Último (20)

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

Angular 4 with firebase

  • 1. Angular 4 with Firebase FAST TRACK YOUR DEV Annie Bougie Senior Developer, Concurrency, Inc @bougiefever anne.bougie@gmail.com
  • 2. Why is Developing a New Site So Hard? • Build a UI • Make it Responsive • Build an API • Data Modeling • Authentication • Security • Hosting • Notifications • How much will it cost?
  • 4. Starting A New App? Angular 4 Is A Good Choice ◦Modularized components are maintainable ◦Cross platform support ◦GoodTooling ◦Large Dev Community
  • 5. What About Everything Else? ◦ REST Api ◦ Hosting ◦ Automatic Scaling ◦ Authentication ◦ File Storage ◦ SSL ◦ Analytics ◦ Cloud Messaging
  • 6. Realtime NoSQL Database ◦ All clients subscribe to one database instance ◦ Interact asynchronously with RxJs Observables
  • 9.
  • 12. Firebase (NoSQL) Data Modeling Avoid deeply nested hierarchies Use association tables to link records
  • 13. -| events -| instructors -| scheduledEvents -| eventInstructorLink -| eventKey -| instructorKey (1 or more) -| instructorEventLink -| instructorKey -| eventKey (1 or more) -| comments -| scheduledEventId
  • 15. Setting up Angular for Firebase PREREQUISITES Node.js 6.9.0 or higher Npm 3 or higher RECOMMENDED SOFTWARE VSCode, WebStorm, Sublime Yarn
  • 16. Download and install node from nodejs.org npm install –g @angular/cli npm install –g typescript npm install –g typings ng new <project-name> npm install firebase, angularfire2 --save
  • 17. AngularFire2 Observable based - Use the power of RxJS, Angular, and Firebase. Realtime bindings - Synchronize data in reatime. Authentication - Log users in with a variety of providers and monitor authentication state in realtime.
  • 18. firebase SDK ◦ For when you need more functionality than what AngularFire2 offers ◦ Not an NgModule
  • 19. Copy config values into src/environments/environment.ts in Angular App
  • 20. Add Firebase Config export const environment = { production: false, firebaseConfig: { apiKey: "AIzaSyCbVRqtVxNZBb6b0ie34wJdC3OjBHSA5DE", authDomain: "fir-demo-1238d.firebaseapp.com", databaseURL: "https://fir-demo-1238d.firebaseio.com", projectId: "fir-demo-1238d", storageBucket: "fir-demo-1238d.appspot.com", messagingSenderId: "398640249561" } };
  • 21. import { AngularFireModule } from 'angularfire2'; import { AngularFireDatabaseModule } from ‘angularfire2/database’; import { environment } from '../environments/environment’; /// omit code /// @NgModule({ imports: [ AngularFireModule.initializeApp(environment.firebaseConfig), AngularFireDatabaseModule, AngularFireAuthModule, /// omit code /// export class AppModule { } Root Angular Module
  • 22. Save and Retrieve Data ANGULAR FIRE DATABASE & ANGULAR FIRE APP
  • 23. Retrieving Firebase Data ◦ Get a reference to the node ◦ Add any query or limits to the data you want to retrieve ◦ Subscribe to the data
  • 24. Getting Firebase Objects The Code constructor(private db: AngularFireDatabase) { const pathToObject = '/events/1’; this.event$ = this.db.object(pathToObject); } The HTML <p> {{ (event$ | async)?.name }} </p>
  • 25. Getting Firebase Lists The Code The HTML constructor(private db: AngularFireDatabase) { this.events$ = db.list("events"); } <ul> <li *ngFor="let event of (events$ | async)">{{event.name}}</li> </ul>
  • 26. Saving to Firebase ◦ Push to list – Firebase determines the key ◦ Update an object – Only updates properties you specify ◦ Set an object – Replaces the object ◦ Atomic saves using the firebaseSDK ◦ REST
  • 27. Updating Objects in Firebase REPLACING OBJECTS WITH SET UPDATING OBJECTS WITH UPDATE this.db.object(this.pathToObject) .set(event); this.db.object(this.pathToObject) .update( {like: 'someone likes this’} );
  • 28. Pushing To A Firebase List events$: FirebaseListObservable<any>; constructor(private db: AngularFireDatabase) { this.events$ = db.list("events"); } addEvent(name) { this.events$.push({name: name}); }
  • 29. Firebase Push Keys ◦ Encoded time stamp ◦ Unique ID ◦ Accessed with the $key attribute
  • 30. Atomic Saves with the Firebase SDK constructor( private db: AngularFireDatabase, @Inject(FirebaseApp) firebaseApp: FirebaseApp) { this.database = firebaseApp.database(); } like() { let likesRef = this.database.ref('likes’); let likePushKey = likesRef.push().key; /// omitted /// let saveObjects = {}; saveObjects[`events/${eventKey}`] = likedEvent; saveObjects[`likes/${likePushKey}/${eventKey}`] = true; this.database.ref().update(saveObjects); }
  • 32. Quick Hosting in Firebase npm install –g firebase-tools firebase login firebase init firebase deploy
  • 34. Firebase Queue Node app Listens on a queue and processes each message that arrives
  • 35. Firebase Auth & Auth ANONYMOUS, EMAIL & PASSWORD, SOCIAL
  • 36. Firebase Authentication ◦ You must enable the types of authentication you want to use. ◦ Social authentication requires further set up
  • 37. Add Firebase Authentication to Angular import { AngularFireAuthModule } from "angularfire2/auth"; imports: [ AngularFireModule.initializeApp(environment.firebaseConfig), AngularFireDatabaseModule, AngularFireAuthModule,
  • 38. Track Authentication State constructor( private angularFireAuth: AngularFireAuth, private snackbar: MdSnackBar ) { this.angularFireAuth.authState.subscribe(auth => this.authState = auth); } get authenticated(): boolean { return this.authState !== null; } get currentUser(): any { return this.authenticated ? this.authState : null; }
  • 39. Login anonymousLogin() { return this.angularFireAuth.auth.signInAnonymously() .then((user) => { this.authState = user; }) .catch(error => console.log(error)); } googleSignIn() { const provider = new firebase.auth.GoogleAuthProvider() return this.angularFireAuth.auth.signInWithPopup(provider) .then((credential) => this.authState = credential.user) .catch(error => console.log(error)); }
  • 40. Logout logout() { this.angularFireAuth.auth.signOut() .then(() => this.authState = null) .catch(error => console.log(error));; }
  • 41. Firebase Push Notifications BROWSER SERVICE WORKER WITH CLOUD SERVICES
  • 43. Set up Angular App For Messaging Add manifest.json Add firebase-messaging-sw.js Save messaging token Receive messages
  • 44. manifest.json { "short_name": "LibraryEvents", "name": "Event Tracker for Libraries", "gcm_sender_id": "103953800507" }
  • 45. firebase-messaging-sw.js Copy messaging id from firebase config importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js'); var config = { messagingSenderId: "346952864544" }; firebase.initializeApp(config); const messaging = firebase.messaging();
  • 46. Set up Angular import { AngularFireAuth } from 'angularfire2/auth'; import { FirebaseApp } from 'angularfire2'; import * as firebase from 'firebase’; ... messaging = firebase.messaging(); ... this.messaging.requestPermission() ... this.messaging.getToken(); ... this.messaging.onMessage((payload: any) => { ... });
  • 49. Cloud Function to Send Notifications ◦ Listen when a data event happens ◦ Send notification to users who have granted permission ◦ Cloud functions are Node apps
  • 51.
  • 52. const functions = require('firebase-functions'); const admin = require('firebase-admin'); const dateformat = require('dateformat'); exports.notifyScheduledEventFunction = functions.database.ref('/scheduledEvents/{scheduledEventId}').onCreate(event => { const libararyEvent = event.data.val(); const scheduledEventId = event.params.scheduledEventId; const db = admin.database(); db.ref(`/scheduledEvents/${scheduledEventId}`).once('value', snapshot => { let se = snapshot.val(); const payload = { notification: { title: se.eventName, body: se.eventName + ' was scheduled on ' + dateformat(se.eventDate, 'mm/dd') + ' by ' + se.instructorName, icon: "https://placeimg.com/250/250" } }; db.ref('/tokens').once('value').then(tokens => { tokens.forEach(function(token) { var data = token.val(); admin.messaging().sendToDevice(data.token, payload) }); }); });
  • 53. Resources Annie Bougie @bougiefever Demo code: https://github.com/Bougiefever/firebase-simple-demo Firebase Queue Sample code: https://github.com/Bougiefever/library-events-likes Library Events App: https://github.com/Bougiefever/library-events-manager Firebase Blog: https://firebase.googleblog.com/ How To Firebase: https://howtofirebase.com/ Angular with Firebase Blog: https://angularfirebase.com/ Angular University: https://angular-university.io/ Egghead: Courses on both Angular and Firebase: https://egghead.io/

Notas del editor

  1. Talk about library project
  2. Firebase console demo