Skip to content

Instantly share code, notes, and snippets.

@DennisSmolek
Created February 19, 2018 14:06
Show Gist options
  • Select an option

  • Save DennisSmolek/c1b74f3b7fa6a81cdcc79173ee3de515 to your computer and use it in GitHub Desktop.

Select an option

Save DennisSmolek/c1b74f3b7fa6a81cdcc79173ee3de515 to your computer and use it in GitHub Desktop.
key$ Observable Operator for Firebase & AngularFire2
// == Custom observable operator to get firebase keys onto a stream with the standard valueChanges()
// Code based on: https://github.com/ReactiveX/rxjs/blob/master/doc/operator-creation.md
export function key$() {
// We *could* do a `var self = this;` here to close over, but see next comment
return Observable.create(subscriber => {
// because we're in an arrow function `this` is from the outer scope.
// var source = this;
// save our inner subscription
var subscription = this.subscribe(value => {
// important: catch errors from user-provided callbacks
try {
// if the value is an array
if (Array.isArray(value))
subscriber.next(value.map(action => ({ key: action.key, $key: action.key, ...action.payload.val() })))
else subscriber.next({ key: value.key, ...value.payload.val()});
} catch(err) { subscriber.error(err); }
},
// be sure to handle errors and completions as appropriate and
// send them along
err => subscriber.error(err),
() => subscriber.complete());
// to return now
return subscription;
});
}
Observable.prototype.key$ = key$;
declare module "rxjs/Observable" {
interface Observable<T> {
key$: typeof key$;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment