├── .angular-cli.json ├── .editorconfig ├── .gitignore ├── README.md ├── e2e ├── app.e2e-spec.ts ├── app.po.ts └── tsconfig.e2e.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── protractor.conf.js ├── src ├── app │ ├── app-routing.module.ts │ ├── app.module.ts │ ├── state │ │ ├── posts │ │ │ ├── index.ts │ │ │ ├── post.actions.ts │ │ │ ├── post.facade.ts │ │ │ ├── post.model.ts │ │ │ └── post.reducer.ts │ │ ├── state.module.ts │ │ ├── state.ts │ │ └── users │ │ │ ├── index.ts │ │ │ ├── user.actions.ts │ │ │ ├── user.facade.ts │ │ │ ├── user.model.ts │ │ │ └── user.reducer.ts │ ├── utils │ │ └── rxjs.operators.ts │ └── views │ │ ├── app.component.html │ │ ├── app.component.scss │ │ └── app.component.ts ├── assets │ ├── .gitkeep │ ├── ngrx-fire-demo.gif │ └── ngrx-firebase.png ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── styles.scss ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── typings.d.ts ├── tsconfig.json └── tslint.json /.angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "project": { 4 | "name": "ngrx-fire" 5 | }, 6 | "apps": [ 7 | { 8 | "root": "src", 9 | "outDir": "dist", 10 | "assets": [ 11 | "assets", 12 | "favicon.ico" 13 | ], 14 | "index": "index.html", 15 | "main": "main.ts", 16 | "polyfills": "polyfills.ts", 17 | "test": "test.ts", 18 | "tsconfig": "tsconfig.app.json", 19 | "testTsconfig": "tsconfig.spec.json", 20 | "prefix": "app", 21 | "styles": [ 22 | "styles.scss" 23 | ], 24 | "scripts": [], 25 | "environmentSource": "environments/environment.ts", 26 | "environments": { 27 | "dev": "environments/environment.ts", 28 | "prod": "environments/environment.prod.ts" 29 | } 30 | } 31 | ], 32 | "e2e": { 33 | "protractor": { 34 | "config": "./protractor.conf.js" 35 | } 36 | }, 37 | "lint": [ 38 | { 39 | "project": "src/tsconfig.app.json", 40 | "exclude": "**/node_modules/**" 41 | }, 42 | { 43 | "project": "src/tsconfig.spec.json", 44 | "exclude": "**/node_modules/**" 45 | }, 46 | { 47 | "project": "e2e/tsconfig.e2e.json", 48 | "exclude": "**/node_modules/**" 49 | } 50 | ], 51 | "test": { 52 | "karma": { 53 | "config": "./karma.conf.js" 54 | } 55 | }, 56 | "defaults": { 57 | "styleExt": "scss", 58 | "component": {} 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | /src/environments/* 8 | 9 | # dependencies 10 | /node_modules 11 | 12 | # IDEs and editors 13 | /.idea 14 | .project 15 | .classpath 16 | .c9/ 17 | *.launch 18 | .settings/ 19 | *.sublime-workspace 20 | 21 | # IDE - VSCode 22 | .vscode/* 23 | !.vscode/settings.json 24 | !.vscode/tasks.json 25 | !.vscode/launch.json 26 | !.vscode/extensions.json 27 | 28 | # misc 29 | /.sass-cache 30 | /connect.lock 31 | /coverage 32 | /libpeerconnection.log 33 | npm-debug.log 34 | testem.log 35 | /typings 36 | yarn-error.log 37 | 38 | # e2e 39 | /e2e/*.js 40 | /e2e/*.map 41 | 42 | # System Files 43 | .DS_Store 44 | Thumbs.db 45 | /src/environments/environment.ts 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NgrxFire 2 | 3 | NgrxFire is a redux demo app created with Angular ngrx and Firebase. Including Firebase Google OAuth and the Realtime Database. 4 | 5 | ## Build your Angular ngrx on a Solid Foundation 6 | 7 | Learn Angular ngrx Redux basics by building this app step-by-step. 8 | 9 | - [Video Lessons and Screencasts](https://angularfirebase.com) 10 | - [Join the Slack Team](https://join.slack.com/angularfirebase/shared_invite/MjA2NTgxMTI0MTk2LTE0OTg4NTQ4MDAtMjhhZDIzMjc0Mg) 11 | 12 | ![](https://firebasestorage.googleapis.com/v0/b/firestarter-96e46.appspot.com/o/assets%2Fngrx-user.gif?alt=media&token=06dab206-2950-4b0f-9d76-fa901d0b267a) 13 | 14 | ## Usage 15 | 16 | #### Clone repository and prepare to build: 17 | 18 | Use the following terminal commands to prepare to build your application: 19 | 20 | - `git clone https://github.com/codediodeio/ngrx-fire.git ngrxFire` 21 | - `cd ngrxFire` 22 | - `npm install` 23 | 24 | #### Create a Firebase account 25 | 26 | * Create a Firebase account at https://firebase.google.com/. 27 | * Configure Authentication for the web app: 28 | > ![firebaseauth](https://user-images.githubusercontent.com/210413/30171158-b036b8dc-93b6-11e7-9698-b355544d0c00.png) 29 | * Seed your Firebase database with sample post data: 30 | > ![ngrxdatabase](https://user-images.githubusercontent.com/210413/30178040-412557c0-93cd-11e7-8218-5f6a70ebca93.png) 31 | ```typescript 32 | { 33 | "posts" : { 34 | "testPost" : { 35 | "text" : "First Post [created in console]", 36 | "votes": 0 37 | } 38 | } 39 | } 40 | ``` 41 | * Gather your Firebase configuration information: 42 | > ![firebaseconfig](https://user-images.githubusercontent.com/210413/30178188-b219c6b4-93cd-11e7-854d-788a2c2d99b1.jpg) 43 | * Create the environment file below `/src/environments/environment.ts`. 44 | ```typescript 45 | export const environment = { 46 | production: false, 47 | firebaseConfig: { 48 | apiKey: 'APIKEY', 49 | authDomain: 'DEV-APP.firebaseapp.com', 50 | databaseURL: 'https://DEV-APP.firebaseio.com', 51 | storageBucket: 'DEV-APP.appspot.com' 52 | } 53 | }; 54 | ``` 55 | * And finally `ng serve` 56 | 57 | 58 | ## Additional Details 59 | 60 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.3.2. 61 | 62 | It uses AngularFire2 v4.0 63 | 64 | Available under the MIT License. 65 | -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('ngrx-fire App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('Welcome to app!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular/cli'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular/cli/plugins/karma') 14 | ], 15 | client:{ 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | reports: [ 'html', 'lcovonly' ], 20 | fixWebpackSourcePaths: true 21 | }, 22 | angularCli: { 23 | environment: 'dev' 24 | }, 25 | reporters: ['progress', 'kjhtml'], 26 | port: 9876, 27 | colors: true, 28 | logLevel: config.LOG_INFO, 29 | autoWatch: true, 30 | browsers: ['Chrome'], 31 | singleRun: false 32 | }); 33 | }; 34 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ngrx-fire", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "ng serve", 8 | "build": "ng build", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "^4.2.4", 16 | "@angular/common": "^4.2.4", 17 | "@angular/compiler": "^4.2.4", 18 | "@angular/core": "^4.2.4", 19 | "@angular/forms": "^4.2.4", 20 | "@angular/http": "^4.2.4", 21 | "@angular/platform-browser": "^4.2.4", 22 | "@angular/platform-browser-dynamic": "^4.2.4", 23 | "@angular/router": "^4.2.4", 24 | "@ngrx/core": "^1.2.0", 25 | "@ngrx/effects": "^4.0.5", 26 | "@ngrx/store": "^4.0.3", 27 | "@ngrx/store-devtools": "^4.0.0", 28 | "angularfire2": "^4.0.0-rc.2", 29 | "core-js": "^2.4.1", 30 | "firebase": "^4.3.0", 31 | "rxjs": "^5.4.2", 32 | "zone.js": "^0.8.14" 33 | }, 34 | "devDependencies": { 35 | "@angular/cli": "1.3.2", 36 | "@angular/compiler-cli": "^4.2.4", 37 | "@angular/language-service": "^4.2.4", 38 | "@types/jasmine": "~2.5.53", 39 | "@types/jasminewd2": "~2.0.2", 40 | "@types/node": "~6.0.60", 41 | "codelyzer": "~3.1.1", 42 | "jasmine-core": "~2.6.2", 43 | "jasmine-spec-reporter": "~4.1.0", 44 | "karma": "~1.7.0", 45 | "karma-chrome-launcher": "~2.1.1", 46 | "karma-cli": "~1.0.1", 47 | "karma-coverage-istanbul-reporter": "^1.2.1", 48 | "karma-jasmine": "~1.1.0", 49 | "karma-jasmine-html-reporter": "^0.2.2", 50 | "protractor": "~5.1.2", 51 | "ts-node": "~3.2.0", 52 | "tslint": "~5.3.2", 53 | "typescript": "~2.3.3" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './e2e/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | 4 | const routes: Routes = [ 5 | { 6 | path: '', 7 | children: [] 8 | } 9 | ]; 10 | 11 | @NgModule({ 12 | imports: [RouterModule.forRoot(routes)], 13 | exports: [RouterModule] 14 | }) 15 | export class AppRoutingModule { } 16 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | 4 | // ************************* 5 | // Custom Application imports 6 | // ************************* 7 | 8 | import { AppRoutingModule } from './app-routing.module'; 9 | import { AppStateModule } from './state/state.module'; 10 | 11 | import { AppComponent } from './views/app.component'; 12 | 13 | @NgModule({ 14 | imports: [ 15 | BrowserModule, 16 | AppRoutingModule, 17 | AppStateModule, 18 | ], 19 | declarations: [ AppComponent ], 20 | bootstrap: [ AppComponent ], 21 | providers: [] 22 | }) 23 | export class AppModule { } 24 | -------------------------------------------------------------------------------- /src/app/state/posts/index.ts: -------------------------------------------------------------------------------- 1 | export * from './post.actions'; 2 | export * from './post.model'; 3 | export * from './post.reducer'; 4 | export * from './post.facade'; 5 | -------------------------------------------------------------------------------- /src/app/state/posts/post.actions.ts: -------------------------------------------------------------------------------- 1 | import { Action } from '@ngrx/store'; 2 | import { Post } from './post.model'; 3 | 4 | export const GET_POST = 'Post get'; 5 | export const GET_POST_SUCCESS = 'Post get success'; 6 | 7 | export const VOTE_UPDATE = 'Post Vote'; 8 | export const VOTE_SUCCESS = 'Post Vote success'; 9 | export const VOTE_FAIL = 'Post Vote fail'; 10 | 11 | 12 | export class GetPost implements Action { 13 | readonly type = GET_POST; 14 | constructor(public payload: string) {} 15 | } 16 | 17 | export class GetPostSuccess implements Action { 18 | readonly type = GET_POST_SUCCESS; 19 | constructor(public payload: Post) {} 20 | } 21 | 22 | export class VoteUpdate implements Action { 23 | readonly type = VOTE_UPDATE; 24 | constructor(public payload: any) {} 25 | } 26 | 27 | export class VoteSuccess implements Action { 28 | readonly type = VOTE_SUCCESS; 29 | constructor(public payload?: any) {} 30 | } 31 | 32 | export class VoteFail implements Action { 33 | readonly type = VOTE_FAIL; 34 | constructor(public payload?: any) {} 35 | } 36 | 37 | 38 | 39 | export type All 40 | = GetPost 41 | | GetPostSuccess 42 | | VoteUpdate 43 | | VoteSuccess 44 | | VoteFail; 45 | -------------------------------------------------------------------------------- /src/app/state/posts/post.facade.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Store } from '@ngrx/store'; 3 | import { Effect, Actions } from '@ngrx/effects'; 4 | 5 | import { AngularFireDatabase } from 'angularfire2/database'; 6 | 7 | import { Observable } from 'rxjs/Observable'; 8 | import { of } from 'rxjs/observable/of'; 9 | import '../../utils/rxjs.operators'; 10 | 11 | import {AppState} from '../state'; 12 | import {Post} from './post.model'; 13 | import {PostsQuery} from './post.reducer'; 14 | 15 | import { AUTHENTICATED } from '../users/user.actions'; 16 | import * as postActions from './post.actions'; 17 | type Action = postActions.All; 18 | 19 | 20 | @Injectable() 21 | export class PostsFacade { 22 | 23 | // ************************************************ 24 | // Observable Queries available for consumption by views 25 | // ************************************************ 26 | 27 | post$ = this.store.select(PostsQuery.getPost); 28 | 29 | // ************************************************ 30 | // Effects to be registered at the Module level 31 | // ************************************************ 32 | @Effect() 33 | init$: Observable = this.actions$.ofType(AUTHENTICATED) 34 | .map(_ => new postActions.GetPost('/posts/testPost')); 35 | 36 | 37 | @Effect() 38 | getPost$: Observable = this.actions$.ofType(postActions.GET_POST) 39 | .map((action: postActions.GetPost) => action.payload ) 40 | .delay(2000) // delay to show spinner 41 | .mergeMap(payload => this.db.object(payload)) 42 | .map(post => { 43 | post.pushKey = post.$key; 44 | return new postActions.GetPostSuccess(post); 45 | }); 46 | 47 | 48 | @Effect() 49 | voteUpdate: Observable = this.actions$.ofType(postActions.VOTE_UPDATE) 50 | .map((action: postActions.VoteUpdate) => action.payload ) 51 | .mergeMap(payload => of(this.db.object('posts/' + payload.post.pushKey) 52 | .update({ 53 | votes: payload.post.votes + payload.val 54 | }))) 55 | 56 | .map(() => new postActions.VoteSuccess()) 57 | .catch(err => of (new postActions.VoteFail( { error: err.message } )) ); 58 | 59 | // ************************************************ 60 | // Internal Code 61 | // ************************************************ 62 | 63 | constructor( 64 | private actions$: Actions, 65 | private store: Store, 66 | private db: AngularFireDatabase 67 | ) { } 68 | 69 | 70 | loadPost(name = 'testPost'): Observable { 71 | this.store.dispatch(new postActions.GetPost(`/posts/${name}`)); 72 | return this.post$; 73 | } 74 | 75 | vote(post: Post, val: number):void { 76 | this.store.dispatch(new postActions.VoteUpdate({ post, val })); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/app/state/posts/post.model.ts: -------------------------------------------------------------------------------- 1 | export interface Post { 2 | pushKey: string; 3 | loading: boolean; 4 | text: string; 5 | votes: number; 6 | error?: string; 7 | } 8 | -------------------------------------------------------------------------------- /src/app/state/posts/post.reducer.ts: -------------------------------------------------------------------------------- 1 | import { AppState } from '../state'; 2 | 3 | import * as PostActions from './post.actions'; 4 | import { Post } from './post.model'; 5 | 6 | export type Action = PostActions.All; 7 | 8 | /** 9 | * Define all store queries for Post(s) 10 | */ 11 | export namespace PostsQuery { 12 | export const getPost = (state: AppState) => state.post; 13 | } 14 | 15 | 16 | /// Reducer function 17 | export function postReducer(state: Post, action: Action) { 18 | 19 | switch (action.type) { 20 | 21 | case PostActions.GET_POST: 22 | return { ...state, loading: true }; 23 | 24 | case PostActions.GET_POST_SUCCESS: 25 | return { ...state, ...action.payload, loading: false }; 26 | 27 | case PostActions.VOTE_UPDATE: 28 | return { ...state, ...action.payload, loading: true }; 29 | 30 | case PostActions.VOTE_SUCCESS: 31 | return { ...state, loading: false }; 32 | 33 | case PostActions.VOTE_FAIL: 34 | return { ...state, ...action.payload, loading: false }; 35 | 36 | default: 37 | return state; 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/app/state/state.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | 3 | import { AngularFireModule } from 'angularfire2'; 4 | import { AngularFireDatabaseModule } from 'angularfire2/database'; 5 | import { AngularFireAuthModule } from 'angularfire2/auth'; 6 | 7 | import { EffectsModule } from '@ngrx/effects'; 8 | import { StoreModule } from '@ngrx/store'; 9 | import { StoreDevtoolsModule } from '@ngrx/store-devtools'; 10 | 11 | // ************************* 12 | // Custom Application imports 13 | // ************************* 14 | 15 | import { postReducer } from './posts/post.reducer'; 16 | import { userReducer } from './users/user.reducer'; 17 | 18 | import {UserFacade} from './users'; 19 | import {PostsFacade} from './posts'; 20 | 21 | import { environment } from '../../environments/environment'; 22 | export const firebaseConfig = environment.firebaseConfig; 23 | 24 | @NgModule({ 25 | imports: [ 26 | AngularFireModule.initializeApp(firebaseConfig), 27 | AngularFireDatabaseModule, 28 | AngularFireAuthModule, 29 | 30 | EffectsModule.forRoot([ 31 | UserFacade, 32 | PostsFacade 33 | ]), 34 | 35 | // Signature matches AppState interface 36 | StoreModule.forRoot({ 37 | post: postReducer, 38 | user: userReducer 39 | }), 40 | 41 | StoreDevtoolsModule.instrument({ maxAge: 25 }) 42 | ], 43 | providers: [ 44 | UserFacade, 45 | PostsFacade 46 | ], 47 | }) 48 | export class AppStateModule { } 49 | -------------------------------------------------------------------------------- /src/app/state/state.ts: -------------------------------------------------------------------------------- 1 | import {Post} from './posts'; 2 | import {User} from './users'; 3 | 4 | export interface AppState { 5 | post: Post; 6 | user: User; 7 | } 8 | -------------------------------------------------------------------------------- /src/app/state/users/index.ts: -------------------------------------------------------------------------------- 1 | export * from './user.actions'; 2 | export * from './user.model'; 3 | export * from './user.reducer'; 4 | export * from './user.facade'; 5 | -------------------------------------------------------------------------------- /src/app/state/users/user.actions.ts: -------------------------------------------------------------------------------- 1 | import { Action } from '@ngrx/store'; 2 | import { User } from './user.model'; 3 | 4 | export const GET_USER = '[Auth] Get user'; 5 | export const AUTHENTICATED = '[Auth] Authenticated'; 6 | export const NOT_AUTHENTICATED = '[Auth] Not Authenticated'; 7 | 8 | export const GOOGLE_LOGIN = '[Auth] Google login attempt'; 9 | export const LOGOUT = '[Auth] Logout'; 10 | 11 | export const AUTH_ERROR = '[Auth] Error'; 12 | 13 | 14 | /// Get User AuthState 15 | 16 | export class GetUser implements Action { 17 | readonly type = GET_USER; 18 | constructor(public payload?: any) {} 19 | } 20 | 21 | export class Authenticated implements Action { 22 | readonly type = AUTHENTICATED; 23 | constructor(public payload?: any) {} 24 | } 25 | 26 | export class NotAuthenticated implements Action { 27 | readonly type = NOT_AUTHENTICATED; 28 | constructor(public payload?: any) {} 29 | } 30 | 31 | export class AuthError implements Action { 32 | readonly type = AUTH_ERROR; 33 | constructor(public payload?: any) {} 34 | } 35 | 36 | /// Google Login Actions 37 | 38 | export class GoogleLogin implements Action { 39 | readonly type = GOOGLE_LOGIN; 40 | constructor(public payload?: any) {} 41 | } 42 | 43 | /// Logout Actions 44 | 45 | export class Logout implements Action { 46 | readonly type = LOGOUT; 47 | constructor(public payload?: any) {} 48 | } 49 | 50 | 51 | export type All 52 | = GetUser 53 | | Authenticated 54 | | NotAuthenticated 55 | | GoogleLogin 56 | | AuthError 57 | | Logout; 58 | -------------------------------------------------------------------------------- /src/app/state/users/user.facade.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Store } from '@ngrx/store'; 3 | import { Effect, Actions } from '@ngrx/effects'; 4 | 5 | import * as firebase from 'firebase'; 6 | import { AngularFireDatabase } from 'angularfire2/database'; 7 | import { AngularFireAuth } from 'angularfire2/auth'; 8 | 9 | import { Observable } from 'rxjs/Observable'; 10 | import { defer } from 'rxjs/observable/defer'; 11 | import '../../utils/rxjs.operators'; 12 | 13 | import {AppState} from '../state'; 14 | import {User} from './user.model'; 15 | import {UsersQuery} from './user.reducer'; 16 | 17 | import * as userActions from './user.actions'; 18 | type Action = userActions.All; 19 | 20 | 21 | @Injectable() 22 | export class UserFacade { 23 | 24 | // ************************************************ 25 | // Observable Queries available for consumption by views 26 | // ************************************************ 27 | 28 | user$ = this.store.select(UsersQuery.getUser); 29 | 30 | // ************************************************ 31 | // Effects to be registered at the Module level 32 | // ************************************************ 33 | 34 | @Effect() getUser$: Observable = this.actions$.ofType(userActions.GET_USER) 35 | .map((action: userActions.GetUser) => action.payload ) 36 | .switchMap(payload => this.afAuth.authState ) 37 | .delay(2000) // delay to show loading spinner, delete me! 38 | .map( authData => { 39 | if (authData) { 40 | /// User logged in 41 | const user = new User(authData.uid, authData.displayName); 42 | return new userActions.Authenticated(user); 43 | } else { 44 | /// User not logged in 45 | return new userActions.NotAuthenticated(); 46 | } 47 | 48 | }) 49 | .catch(err => Observable.of(new userActions.AuthError()) ); 50 | 51 | 52 | /** 53 | * Login with Google OAuth 54 | */ 55 | @Effect() login$: Observable = this.actions$.ofType(userActions.GOOGLE_LOGIN) 56 | .map((action: userActions.GoogleLogin) => action.payload) 57 | .switchMap(payload => { 58 | return Observable.fromPromise( this.googleLogin() ); 59 | }) 60 | .map( credential => { 61 | // successful login 62 | return new userActions.GetUser(); 63 | }) 64 | .catch(err => { 65 | return Observable.of(new userActions.AuthError({error: err.message})); 66 | }); 67 | 68 | 69 | @Effect() logout$: Observable = this.actions$.ofType(userActions.LOGOUT) 70 | .map((action: userActions.Logout) => action.payload ) 71 | .switchMap(payload => { 72 | return Observable.of( this.afAuth.auth.signOut() ); 73 | }) 74 | .map( authData => { 75 | return new userActions.NotAuthenticated(); 76 | }) 77 | .catch(err => Observable.of(new userActions.AuthError({error: err.message})) ); 78 | 79 | 80 | @Effect({dispatch: false}) 81 | init$: Observable = defer(() => { 82 | this.store.dispatch(new userActions.GetUser()); 83 | }); 84 | 85 | // ************************************************ 86 | // Internal Code 87 | // ************************************************ 88 | 89 | constructor( 90 | private actions$: Actions, 91 | private store: Store, 92 | private afAuth: AngularFireAuth, 93 | private db: AngularFireDatabase 94 | ) { } 95 | 96 | /** 97 | * 98 | */ 99 | login() : Observable { 100 | this.store.dispatch(new userActions.GoogleLogin()); 101 | return this.user$; 102 | } 103 | 104 | /** 105 | * 106 | */ 107 | logout() : Observable { 108 | this.store.dispatch(new userActions.Logout()); 109 | return this.user$; 110 | } 111 | 112 | // ****************************************** 113 | // Internal Methods 114 | // ****************************************** 115 | 116 | 117 | protected googleLogin(): firebase.Promise { 118 | const provider = new firebase.auth.GoogleAuthProvider(); 119 | return this.afAuth.auth.signInWithPopup(provider); 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/app/state/users/user.model.ts: -------------------------------------------------------------------------------- 1 | export interface IUser { 2 | uid: string; 3 | displayName: string; 4 | loading?: boolean; 5 | error?: string; 6 | } 7 | 8 | export class User { 9 | constructor(public uid: string, public displayName: string) {} 10 | } 11 | -------------------------------------------------------------------------------- /src/app/state/users/user.reducer.ts: -------------------------------------------------------------------------------- 1 | import { AppState } from '../state'; 2 | 3 | import * as userActions from './user.actions'; 4 | import { User } from './user.model'; 5 | 6 | export type Action = userActions.All; 7 | 8 | const defaultUser = new User(null, 'GUEST'); 9 | 10 | /** 11 | * Define all store queries for Post(s) 12 | */ 13 | export namespace UsersQuery { 14 | export const getUser = (state: AppState) => state.user; 15 | } 16 | 17 | 18 | /// Reducer function 19 | export function userReducer(state: User = defaultUser, action: Action) { 20 | switch (action.type) { 21 | 22 | case userActions.GET_USER: 23 | return { ...state, loading: true }; 24 | 25 | case userActions.AUTHENTICATED: 26 | return { ...state, ...action.payload, loading: false }; 27 | 28 | case userActions.NOT_AUTHENTICATED: 29 | return { ...state, ...defaultUser, loading: false }; 30 | 31 | case userActions.GOOGLE_LOGIN: 32 | return { ...state, loading: true }; 33 | 34 | case userActions.AUTH_ERROR: 35 | return { ...state, ...action.payload, loading: false }; 36 | 37 | case userActions.LOGOUT: 38 | return { ...state, loading: true }; 39 | 40 | default: 41 | return state; 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/app/utils/rxjs.operators.ts: -------------------------------------------------------------------------------- 1 | 2 | import 'rxjs/add/observable/fromPromise'; 3 | import 'rxjs/add/observable/of'; 4 | 5 | import 'rxjs/add/operator/map'; 6 | import 'rxjs/add/operator/mergeMap'; 7 | import 'rxjs/add/operator/switchMap'; 8 | 9 | import 'rxjs/add/operator/catch'; 10 | import 'rxjs/add/operator/delay'; 11 | -------------------------------------------------------------------------------- /src/app/views/app.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 | 5 |

ngrxFire

6 | 7 | demo app with ngrx and firebase 8 | 9 |
10 | 11 | 12 |
13 | 14 | 15 | 16 |

Howdy, {{ user.displayName }}

17 |

{{ user.uid }}

18 | 19 | 29 | 30 | 31 | 32 |
33 | 34 | 35 |
36 | 37 |
38 | 39 | 40 | 41 | 42 |

{{ post.text }}

43 |

Votes: {{ post.votes }}

44 | 45 |
46 | 47 | 48 | 49 | 50 | 51 |
52 | 53 | 54 | 55 | 56 |
57 | 58 | 59 | 60 | 61 | 62 |
63 |
64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/app/views/app.component.scss: -------------------------------------------------------------------------------- 1 | i { font-size: 2em; } 2 | button { margin-bottom: 10px; } -------------------------------------------------------------------------------- /src/app/views/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import {Post} from '../state/posts'; 6 | import {User} from '../state/users'; 7 | 8 | import {UserFacade} from '../state/users/user.facade'; 9 | import {PostsFacade} from '../state/posts/post.facade'; 10 | 11 | 12 | @Component({ 13 | selector: 'app-root', 14 | templateUrl: './app.component.html', 15 | styleUrls: ['./app.component.scss'] 16 | }) 17 | export class AppComponent { 18 | 19 | post$: Observable = this.postService.post$; 20 | user$: Observable = this.userService.user$; 21 | 22 | constructor(private userService:UserFacade, private postService:PostsFacade) { } 23 | 24 | login() { this.userService.login(); } 25 | logout() { this.userService.logout(); } 26 | 27 | vote(post: Post, val: number) { 28 | this.postService.vote(post, val); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codediodeio/ngrx-fire/9ca4ec470563eabd663b413aa59c2ba0b3b7ab4d/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/assets/ngrx-fire-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codediodeio/ngrx-fire/9ca4ec470563eabd663b413aa59c2ba0b3b7ab4d/src/assets/ngrx-fire-demo.gif -------------------------------------------------------------------------------- /src/assets/ngrx-firebase.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codediodeio/ngrx-fire/9ca4ec470563eabd663b413aa59c2ba0b3b7ab4d/src/assets/ngrx-firebase.png -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codediodeio/ngrx-fire/9ca4ec470563eabd663b413aa59c2ba0b3b7ab4d/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NgrxFire 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule); 12 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** Evergreen browsers require these. **/ 41 | import 'core-js/es6/reflect'; 42 | import 'core-js/es7/reflect'; 43 | 44 | 45 | /** 46 | * Required to support Web Animations `@angular/animation`. 47 | * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation 48 | **/ 49 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 50 | 51 | 52 | 53 | /*************************************************************************************************** 54 | * Zone JS is required by Angular itself. 55 | */ 56 | import 'zone.js/dist/zone'; // Included with Angular CLI. 57 | 58 | 59 | 60 | /*************************************************************************************************** 61 | * APPLICATION IMPORTS 62 | */ 63 | 64 | /** 65 | * Date, currency, decimal and percent pipes. 66 | * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 67 | */ 68 | // import 'intl'; // Run `npm install --save intl`. 69 | /** 70 | * Need to import at least one locale-data with intl. 71 | */ 72 | // import 'intl/locale-data/jsonp/en'; 73 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare const __karma__: any; 17 | declare const require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | const context = require.context('./', true, /\.spec\.ts$/); 29 | // And load the modules. 30 | context.keys().map(context); 31 | // Finally, start Karma to run the tests. 32 | __karma__.start(); 33 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "baseUrl": "./", 6 | "module": "es2015", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts" 15 | ], 16 | "include": [ 17 | "**/*.spec.ts", 18 | "**/*.d.ts" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "sourceMap": true, 6 | "declaration": false, 7 | "moduleResolution": "node", 8 | "emitDecoratorMetadata": true, 9 | "experimentalDecorators": true, 10 | "target": "es5", 11 | "typeRoots": [ 12 | "node_modules/@types" 13 | ], 14 | "lib": [ 15 | "es2017", 16 | "dom" 17 | ] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "eofline": true, 15 | "forin": true, 16 | "import-blacklist": [ 17 | true, 18 | "rxjs" 19 | ], 20 | "import-spacing": false, 21 | "indent": [ 22 | true, 23 | "spaces" 24 | ], 25 | "interface-over-type-literal": true, 26 | "label-position": true, 27 | "max-line-length": [ 28 | true, 29 | 140 30 | ], 31 | "member-access": false, 32 | "member-ordering": [ 33 | true, 34 | { 35 | "order": [ 36 | "static-field", 37 | "instance-field", 38 | "static-method", 39 | "instance-method" 40 | ] 41 | } 42 | ], 43 | "no-arg": true, 44 | "no-bitwise": true, 45 | "no-console": [ 46 | true, 47 | "debug", 48 | "info", 49 | "time", 50 | "timeEnd", 51 | "trace" 52 | ], 53 | "no-construct": true, 54 | "no-debugger": true, 55 | "no-duplicate-super": true, 56 | "no-empty": false, 57 | "no-empty-interface": true, 58 | "no-eval": true, 59 | "no-inferrable-types": [ 60 | true, 61 | "ignore-params" 62 | ], 63 | "no-misused-new": true, 64 | "no-non-null-assertion": true, 65 | "no-shadowed-variable": true, 66 | "no-string-literal": false, 67 | "no-string-throw": true, 68 | "no-switch-case-fall-through": true, 69 | "no-trailing-whitespace": false, 70 | "no-unnecessary-initializer": true, 71 | "no-unused-expression": true, 72 | "no-use-before-declare": true, 73 | "no-var-keyword": true, 74 | "object-literal-sort-keys": false, 75 | "one-line": [ 76 | true, 77 | "check-open-brace", 78 | "check-catch", 79 | "check-else", 80 | "check-whitespace" 81 | ], 82 | "prefer-const": true, 83 | "quotemark": [ 84 | true, 85 | "single" 86 | ], 87 | "radix": true, 88 | "semicolon": [ 89 | true, 90 | "always" 91 | ], 92 | "triple-equals": [ 93 | true, 94 | "allow-null-check" 95 | ], 96 | "typedef-whitespace": [ 97 | true, 98 | { 99 | "call-signature": "nospace", 100 | "index-signature": "nospace", 101 | "parameter": "nospace", 102 | "property-declaration": "nospace", 103 | "variable-declaration": "nospace" 104 | } 105 | ], 106 | "typeof-compare": true, 107 | "unified-signatures": true, 108 | "variable-name": false, 109 | "whitespace": [ 110 | true, 111 | "check-branch", 112 | "check-decl", 113 | "check-operator", 114 | "check-separator", 115 | "check-type" 116 | ], 117 | "directive-selector": [ 118 | true, 119 | "attribute", 120 | "app", 121 | "camelCase" 122 | ], 123 | "component-selector": [ 124 | true, 125 | "element", 126 | "app", 127 | "kebab-case" 128 | ], 129 | "use-input-property-decorator": true, 130 | "use-output-property-decorator": true, 131 | "use-host-property-decorator": true, 132 | "no-input-rename": true, 133 | "no-output-rename": true, 134 | "use-life-cycle-interface": true, 135 | "use-pipe-transform-interface": true, 136 | "component-class-suffix": true, 137 | "directive-class-suffix": true, 138 | "no-access-missing-member": true, 139 | "templates-use-public": true, 140 | "invoke-injectable": true 141 | } 142 | } 143 | --------------------------------------------------------------------------------