Firebaseへのアクセスを提供するAngularサービスがあります。Firebaseからデータを取得し、その情報を配列に入れて、初期化された配列でいくつかの関数を呼び出すコンポーネントがあります。私はAngularを初めて使用するため、この動作をどのように実装すべきか正確にはわかりません。subscribe()は非同期であることがわかっているので、これに敏感になるように関数を実装する必要があります。
graph.component.ts
import { Component, OnInit, OnChanges, ViewChild, ElementRef, Input, ViewEncapsulation } from '@angular/core';
import { EscortService } from '../services/escort/escort.service';
import { Escort } from '../data/escort.data';
import * as d3 from 'd3';
@Component({
selector: 'app-graph',
templateUrl: './graph.component.html',
styleUrls: ['./graph.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class GraphComponent implements OnInit {
escortList : Escort[] = [];
constructor(private escortService : EscortService, private element: ElementRef){
}
ngOnInit(){
this.getData();
this.generateBarChart();
}
getData(){
var esc = this.escortService.getData();
esc.snapshotChanges().subscribe(item => {
this.escortList = [];
item.forEach(element => {
var y = element.payload.toJSON();
y["$key"] = element.key;
var currentEscort = (y as Escort);
if(currentEscort.status == 'Completed'){
console.log("escort-list -> ngOnInit() : currentEscort.status = " + currentEscort.status);
this.escortList.push(currentEscort);
}
});
});
}
escortListはObservableである必要があります。
private const escortList = new ReplaySubject<Escort[]>();
get escortList() : Observable<Escort[]> {
return this.escortList.asObservable(); // this prevents caller from being able to call method 'next' on the subject
}
constructor(private escortService : EscortService, private element: ElementRef){
}
ngOnInit(){
this.getData();
this.generateBarChart();
}
getData(){
var esc = this.escortService.getData();
esc.snapshotChanges().subscribe(item => {
const newEscortList = [];
item.forEach(element => {
var y = element.payload.toJSON();
y["$key"] = element.key;
var currentEscort = (y as Escort);
if(currentEscort.status == 'Completed'){
console.log("escort-list -> ngOnInit() : currentEscort.status = " + currentEscort.status);
newEscortList.push(currentEscort);
}
});
this.escortList.next(newEscortList);
});
}
次に、コンポーネントで、Observableにサブスクライブして更新を取得する必要があります。退会することを忘れないでください。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加