Reputation: 22744
If I try to use RxJS operators like .take, .skip, etc. on FireBaseListObservable, I get "take is not a function" error:
import {Component} from '@angular/core';
import {AngularFire, FirebaseListObservable} from 'angularfire2';
import {Observable} from 'rxjs';
export class AppComponent {
items: FirebaseListObservable<any>;
constructor(public af: AngularFire) {
// this works
Observable.interval(1000).take(5).subscribe(x => console.log(x));
this.items = af.database.list('/items');
// this does not
this.items.take(1).subscribe();
}
}
Edit: importing .take via import "rxjs/add/operator/take"; did work, though now I have another question:
Why
Observable.interval(1000).take(5).subscribe(x => console.log(x));
works even without importing the take?
And how do I cast Observable to FirebaseListObservable?
Upvotes: 0
Views: 607
Reputation: 58440
RxJS is distributed in a manner that allows it to be imported in its entirety or in small pieces.
For the take
operator and its TypeScript declarations to be included, you could choose to either import RxJS in its entirety:
import * as Rx from "rxjs/Rx";
Or could import only the take
operator that you require:
import "rxjs/add/operator/take";
Note that the AngularFire2 observables implement lift
for composition with operators. The effect of this is that after you use an operator, the type will be Observable<T>
rather than FirebaseListObservable<T>
, so if you are assigning the composed observable to a FirebaseListObservable<T>
variable or property you will need a cast.
For example:
let item = af.database.list('/items').take(1) as FirebaseListObservable<any>;
However, you would only need to do so if you intended to use the variable as a FirebaseListObservable
(it has additional methods). Typically, you'd leave it as an Observable
. (I mentioned this as you had a property with the type FirebaseListObservable<any>
and I've seen this cause confusion in a number of other questions.)
In relation to the errors you've mentioned in comments made against the question, the interplay between imports matters. If you are importing Observable
like this:
import { Observable } from "rxjs";
You will be including RxJS in its entirety and all of the operators should be available when composing FirebaseListObservable
instances.
However, the if the imported Observable
is not used anywhere in the module into which it is imported, it's ignored, and you won't get anything imported. Which is likely why you need the explicit import for take
.
Upvotes: 3