I am running an ionic3 app with Angular4 and angularfire2-Firestore.
How does one go about getting a single object from an Observable. I am looking to return in typescript.
console.log(this.opportunity.title) // "Title1"
In the code below I am using the getOpportunityByIndex() method with index as the parameter. I am getting the following output and I'm not sure what to do next.
Observable {_isScalar: false, source: Observable, operator: MapOperator}
operator:MapOperator {thisArg: undefined, project: ƒ}
source:Observable {_isScalar: false, source: Observable, operator: MapOperator}
_isScalar:false
__proto__:Object
Code
export interface Opportunity { title: string; }
export interface OpportunityId extends Opportunity { id: string; }
opportunities: Observable<OpportunityId[]>;
constructor( public firebaseProvider: FirebaseProvider) {
this.opportunities = this.firebaseProvider.getOpportunities();
}
getOpportunityByIndex(index: number) {
this.opportunity = this.opportunities.map(arr => arr[index]);
console.log(this.opportunity.title);
}
}
FirebaseProviderService
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
export interface Opportunity { title: string; }
export interface OpportunityId extends Opportunity { id?: string; }
@Injectable()
export class FirebaseProvider {
private opportunitiesCollection: AngularFirestoreCollection<OpportunityId>;
opportunity: Opportunity
constructor(afs: AngularFirestore) {
this.opportunitiesCollection = afs.collection<Opportunity>('opportunities');
this.opportunities = this.opportunitiesCollection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Opportunity;
const id = a.payload.doc.id;
return { id, ...data };
});
});
}
getOpportunities() {
return this.opportunities;
}
}