0
私はAngular4とangularfire2-Firestoreでionic3アプリケーションを実行しています。特定のインデックスで観測可能な配列要素を取得する[Typescript]
Observableから1つのオブジェクトを取得する方法を教えてください。私はタイトスクリプトで復帰しようとしています。
console.log(this.opportunity.title) // "Title1"
以下のコードでは、インデックスとしてgetOpportunityByIndex()メソッドを使用しています。私は次の結果を得ています。私は次に何をすべきか分かりません。私はあなたの例this.opportunities
の理解何から
Observable {_isScalar: false, source: Observable, operator: MapOperator}
operator:MapOperator {thisArg: undefined, project: ƒ}
source:Observable {_isScalar: false, source: Observable, operator: MapOperator}
_isScalar:false
__proto__:Object
コード
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;
}
}
それを呼びたい時はいつでも、このメソッドはコンストラクタで素晴らしい実行するようだ行うことができます私は方法をいつでも実行する場合は、しかし、私はopportunity.titleを返すことはできません。アプリがクリックイベントのように読み込まれた後 – jchri853
私は自分の答えをもう少し柔軟に変更し、ケースシナリオを検討しました。 –
素晴らしい!ありがとうございます。Hugo Noro – jchri853