问题
I have a form with two different buttons, one to download data (from Firestore) and one to display it in realtime. For this I have two functions (Angular 8), where one uses valueChanges()
to display data in realtime and the other uses get()
to get the same data and download it.
The user can choose to specify search more or less, so I have quite a lot of code for making the query and this needs to be doubled if I am to use both get()
and valueChanges()
. I am therefore wondering if someone can help me adapt my code with get()
to use valueChanges()
instead, so I can use the same kind of query?
async makeQuery(value) {
var collection: string;
// A lot of code here really, but it basically results in something like this:
return this.query = this.afs.collection<DataItem>('CollectionName', ref => ref.where('datetime', '>=', '2020-01-15T09:51:00.000Z').orderBy('datetime', 'desc').limit(100));
}
async downloadCsv(value) {
this.query = this.makeQuery(value);
this.dataForDownload = await this.getDataForDownload();
this.dataForDownload = JSON.stringify(this.dataForDownload['data']);
console.log('Data: ', this.dataForDownload);
var date = new Date();
var date_str = this.datePipe.transform(date, 'yyyy-MM-ddTHH-mm');
this.makeFileService.downloadFile(this.dataForDownload, 'data-' + date_str);
}
async getDataForDownload() {
return this.query.get()
.then(function (querySnapshot) {
var jsonStr = '{"data":[]}';
var dataObj = JSON.parse(jsonStr); //making object we can push to
querySnapshot.forEach(function (doc) {
//console.log('Data for download: ', JSON.stringify(doc.data()), ', id: ', doc.id);
dataObj['data'].push(doc.data());
});
console.log('The returned dataObj is: ', dataObj);
return dataObj;
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
}
async getRealTimeData(value) {
this.query = await this.makeQuery(value);
this.data = this.query.valueChanges();
}
I am thinking that using RxJS operators like map()
and perhaps take(1)
on valueChanges()
(in a pipe) would work, but I am not getting how this should be done. Just like in the code above (getDataForDownload()
), I need to push objects to a JSON object so that it can be downloaded.
The result I (want to) get is one (or usually many) objects something like so: {timestamp: XXX, ID: XXX, temperature: XXX}, from where the data is to be listed in a CSV file with one object on each row.
来源:https://stackoverflow.com/questions/61340822/how-to-use-valuechanges-instead-of-get-to-download-data-with-json-string