# @blaugold/angular-firebase

> Wrapper around Firebase JS-API for Angular 2 Apps.

Latest version **2.2.2** (published 2017-03-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install @blaugold/angular-firebase
pnpm add @blaugold/angular-firebase
yarn add @blaugold/angular-firebase
bun add @blaugold/angular-firebase
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.2.2 |
| Published | 2017-03-24 |
| First published | 2016-11-03 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=5.0.0 |
| Dependencies | 1 |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| GitHub stars | 4 |
| Author | Gabriel Terwesten |
| Maintainers | blaugold |
| Keywords | Firebase, Angular 2, Observable, RxJS |

## Links

- npm: https://www.npmjs.com/package/@blaugold/angular-firebase
- Repository: https://github.com/blaugold/angular-firebase
- Homepage: https://github.com/blaugold/angular-firebase#readme
- Issues: https://github.com/blaugold/angular-firebase/issues
- npm.io page: https://npm.io/package/@blaugold/angular-firebase

## Dependencies (1)

- [firebase](https://npm.io/package/firebase.md) ^3.7.3

## Recent versions

- 2.2.2 (latest) — 2017-03-24
- 2.2.1 — 2017-03-24
- 2.1.0 — 2017-03-22
- 2.0.0 — 2017-03-18
- 1.0.6 — 2017-03-11
- 1.0.5 — 2017-01-30
- 1.0.3 — 2017-01-30
- 1.0.2 — 2017-01-24
- 1.0.0 — 2016-11-30
- 0.2.0 — 2016-11-14
- 0.1.0 — 2016-11-08
- 0.0.1 — 2016-11-04
- 0.0.0 — 2016-11-04
- 0.0.0-alpha.0-2 — 2016-11-03
- 0.0.0-alpha.0-1 — 2016-11-03
- … 2 more at https://npm.io/package/@blaugold/angular-firebase/versions

## README

## Angular Firebase

[![CircleCI](https://circleci.com/gh/blaugold/angular-firebase.svg?style=svg&circle-token=bf5f61f7f9737852ea53e4e80981312624078636)](https://circleci.com/gh/blaugold/angular-firebase)

Wrapper around Firebase Web-API for Angular Apps.

Most methods found in the Firebase API are present and work the same. For this reason they are not
documented extensively. The Firebase [Guide](https://firebase.google.com/docs/web/setup) and 
[Reference](https://firebase.google.com/docs/reference/) will help understanding how to use the 
library.

The library runs Firebase calls inside zone.js to make change detection work. It is focused on 
observables and returns them for every operation. To make working with observables and 
Firebase easier, the returned observables are extended with helper operators and aliases to snapshot 
methods.

The library support type checking of a database schema to let the compiler catch misspellings and
wrong access patterns.

At the moment Auth and Database are implemented.

**[Reference](https://blaugold.github.io/angular-firebase/index.html)**

## Installation

```
    npm i --save @blaugold/angular-firebase
```

## Usage
For most apps, which only use one firebase project, add the `FirebaseModule` to your root module.

```typescript
import { NgModule } from '@angular/core'
import { FirebaseModule } from '@blaugold/angular-firebase'

@NgModule({
    imports: [
        FirebaseModule.primaryApp({
            options: {
                apiKey: '<your-api-key>',
                authDomain: '<your-auth-domain>',
                databaseURL: '<your-database-url>',
                storageBucket: '<your-storage-bucket>',
                messagingSenderId: '<your-messaging-sender-id>'
            }
        })
    ]
})
export class AppModule {}
```

In your service or component inject `FirebaseDatabase` and `FirebaseAuth`:

```typescript
import { Injectable } from '@angular/core'
import { FirebaseDatabase } from '@blaugold/angular-firebase'
import { Observable } from 'rxjs/Observable'

const todoLists = 'todoLists'

@Injectable()
export class TodoService {

    constructor(private db: FirebaseDatabase<any>) {}
    
    addItem(listId: string, item: TodoItem): Observable<void> {
        return this.db.ref(todoLists).child(listId).push()
            .mergeMap(ref => {
                // Add key as id to item for easier access to id in components
                item.id = ref.key
                return ref.set(item)
            })
    }
    
    // Returns observable of array of 10 last TodoItems 
    onList(listId: string): Observable<TodoItem[]> {
        return this.db.ref(todoLists).child(listId)
            .limitToLast(10)
            // Emits list every time there is a change.
            .onValue()
            // Calls .val() on all children and returns them in an array.
            .toValArray<TodoItem>()
    }
}
```

To use a database schema define interfaces representing the structure of your tree.

```typescript
import { Injectable } from '@angular/core'
import { FirebaseDatabase } from '@blaugold/angular-firebase'
import { Observable } from 'rxjs/Observable'

export interface UserData {
  name: string
  email: string
  signedUpAt: number
}

export interface DatabaseSchema {
  users: {
    [uid: string]: UserData
  }
}

@Injectable()
export class UserService {

  constructor(private db: FirebaseDatabase<DatabaseSchema>) {}
    
  // It is important to either use `db.ref()` without any argument or alternatively declare 
  // the type of the part of the tree the ref points to: `db.ref<UserData>('/users/1')`

  getUserName(uid: string): Observable<string> {
    // No compile error
    return this.db.ref().child('users').child(uid).child('name').val()
  }
  
  getUserEmail(uid: string): Observable<string> {
    // 'user' does not exist at that location in the schema so compiler will complain.  
    return this.db.ref().child('user').child(uid).child('email').val()
  }
}
```

The api mirrors closely how the Firebase Web-API works. The biggest difference is that all 
operations return observables. To get an overview of the api, take a look at [`FirebaseDatabaseRef`](https://blaugold.github.io/angular-firebase/classes/firebasedatabaseref.html), [`DataSnapshotObservable`](https://blaugold.github.io/angular-firebase/classes/datasnapshotobservable.html), [`FirebaseAuth`](https://blaugold.github.io/angular-firebase/classes/firebaseauth.html) and [`FirebaseDatabase`](https://blaugold.github.io/angular-firebase/classes/firebasedatabase.html).

## Multiple Projects
For every project a `FirebaseApp` instance is created. The default project app is injected when
requesting `FirebaseApp`. The default app's `FirebaseDatabase` and `FirebaseAuth`
are available like this as well. To setup additional apps use `FirebaseModule.secondaryApp` and pass
an `InjectionToken` which then can be used to inject the app in services, components, etc.:

```typescript
import { InjectionToken, NgModule, Component, Inject } from '@angular/core'
import { FirebaseModule, FirebaseApp, FirebaseDatabase, FirebaseAuth } from '@blaugold/angular-firebase'

const secondAppToken = new InjectionToken('Second App')

@NgModule({
    imports: [
        FirebaseModule.secondaryApp(secondAppToken, {
            options: {...}
        }),
        FirebaseModule.primaryApp({
            options: {...}
        })
    ]
})
export class AppModule {}

@Component(...)
class AppComponent {
    
    constructor(@Inject(secondAppToken) app: FirebaseApp,
                defaultApp: FirebaseApp,
                defaultDb: FirebaseDatabase,
                defaultAuth: FirebaseAuth) {
        const db = app.database()
        const auth = app.auth()
    }
    
}
```
 
## Operation Invocation
Since the library focuses on observables all operations are invoked lazily as is usually the case 
with observables. This means for example, calling `someRef.set({ foo: 'bar' })` will do nothing 
without either subscribing to the returned observable or calling `toPromise()` on it.

This is in contrast to the Firebase Web-API which starts the operation when the function is
called. It is possible to globally configure the library to behave like the native Firebase Web-API
by calling `setLazyInvocation(false)`

## TODO
- wrap onDisconnect class to include methods in change detection
- Storage
- Messaging

---
_Source: https://npm.io/package/@blaugold/angular-firebase · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
