Steven Giraldo
Steven Giraldo

Reputation: 369

get data from angular firebase firestore database

I have Angular 6, "@angular/fire": "^5.1.1", "firebase": "^5.6.0", and I'm trying of fetch data of my database but it doesn't work.

i have a function called getCadenaFecha(), here i have a logic that take any number of days and subtract them from the current date, then it store in cadena to make a query and fetch data from firestore, when i return the variable ultimoDia, it doesn't fetch the data

This is my code:

import { Injectable } from '@angular/core';
import { tempFirebaseRepo } from './../Repository/tempFirebase'
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import 'rxjs/add/operator/map';

import {Dispositivo} from './../models/Dispositivo';
import {Observable} from 'rxjs';


@Injectable({
    providedIn: 'root'
})
export class query {
    dispositivoRef:AngularFirestoreCollection<Dispositivo>;
    dispositivoRefUno:AngularFirestoreCollection<Dispositivo>;
    dispositivoRefDos:AngularFirestoreCollection<Dispositivo>;
    dispositivoRefTres:AngularFirestoreCollection<Dispositivo>;
    ultimaSemana: Observable<Dispositivo[]>;
    ultimoDia: Observable<Dispositivo[]>;

    constructor(private afs:AngularFirestore, private _tempFirebaseRepo:tempFirebaseRepo){}

    getDia(){

        let cadena=this._tempFirebaseRepo.getCadenaFecha(20)

        //aca esta la query de Firestore
        this.dispositivoRef = this.afs.collection('Dispositivo', ref =>{
            return ref.where('Dispositivo', '>', Number(cadena))
        })
        debugger;
        this.ultimoDia = this.dispositivoRef.valueChanges(); 

        return this.ultimoDia;

    }
}

....and this is my app.module:

          import {BrowserModule} from '@angular/platform-browser';
      import {NgModule} from '@angular/core';
      import {HttpClientModule} from '@angular/common/http';
      import {ChartsModule} from 'ng2-charts';
      import {routing, appRoutingProviders} from './app.routing';
      import {environment} from '../environments/environment';
      import {AngularFirestoreModule} from '@angular/fire/firestore';
      import {AngularFireModule} from '@angular/fire';
      import { tempFirebaseRepo } from './Repository/tempFirebase';

      //componentes
      import { AppComponent } from './app.component';
      import { HeaderComponent } from './components/header/header.component';
      import { FooterComponent } from './components/footer/footer.component';
      import { SettingsComponent } from './components/settings/settings.component';
      import { MenuComponent } from './components/menu/menu.component';
      import { DataComponent } from './components/menu/data/data.component';
      import { InformeMesComponent } from './components/menu/informe/informe-mes/informe-mes.component';


      @NgModule({
        declarations: [
          AppComponent,
          HeaderComponent,
          FooterComponent,
          SettingsComponent,
          MenuComponent,
          DataComponent,
          InformeMesComponent,

        ],
        imports: [
          HttpClientModule,
          BrowserModule,
          ChartsModule,
          routing,
          AngularFirestoreModule,
          AngularFireModule.initializeApp(environment.firebase),
        ],
        providers: [
          appRoutingProviders,
          tempFirebaseRepo
        ],
        bootstrap: [AppComponent]
      })
      export class AppModule { }

...this is my component, here is the subscribe:

        import { Component, OnInit, Input} from '@angular/core';
    import {TemperaturaService} from '../../../services/Temperatura/Temperatura.service';
    //import {tempFirebaseService} from '../../../services/tempFirebase/temp-firebase.service';
    import {Global} from '../../../services/Temperatura/global';
    import {tempFirebaseRepo} from '../../../Repository/tempFirebase'
    import {Observable, Subject} from 'rxjs/Rx';
    import {query} from '../../../Repository/query'

    @Component({
      selector: 'app-data',
      templateUrl: './data.component.html',
      styleUrls: ['./data.component.css'],
      providers: [TemperaturaService, /*tempFirebaseService*/ ]
    })
    export class DataComponent implements OnInit {
      public data:any[];
      public url: string;
      public Chart = [];
      public dia=[];
      public mes=[];
      public year=[];
      public hora=[];
      public minuto=[];
      public medicion=[];
      public fecha=[];
      public Fecha=[];
      public lineChartData:Array<any>=[{data: [], label: ''}];
      public lineChartLabels:Array<any>=this.Fecha;
      public currentDate:number;



      constructor(
        //private _tempFirebaseService: tempFirebaseService,
        private _tempFirebaseRepo:tempFirebaseRepo,
        private _query: query
        ) { 
          this.url = Global.url;    
        }


          ngOnInit() {
            this.getDia();
          }

          //Obtener con api rest
          getDia(){
            this._query.getDia().subscribe(
              response => { 

                this.lineChartData=this._tempFirebaseRepo
                    .OrdenarResponse(response, 
                                      this.fecha, 
                                      this.medicion, 
                                      this.dia, 
                                      this.mes, 
                                      this.year, 
                                      this.hora,
                                      this.minuto, 
                                      this.Fecha,
                                      this.lineChartData
                    );

                debugger;
              },
              error =>{
                console.log(<any>error);
              }
            );
          }
          /*getSemana(){

              this._tempFirebaseService.getUltimaSemana().subscribe(
                  response => { 

                    this.lineChartData=this._tempFirebaseRepo
                        .OrdenarResponse(response, 
                                          this.fecha, 
                                          this.medicion, 
                                          this.dia, 
                                          this.mes, 
                                          this.year, 
                                          this.hora,
                                          this.minuto, 
                                          this.Fecha,
                                          this.lineChartData
                        );

                    debugger;
                  },
                  error =>{
                    console.log(<any>error);
                  }
              );

          }*/
          /* getMes(){
            this._tempFirebaseService.getUltimoMes().subscribe(
              response => { 

                this.lineChartData=this._tempFirebaseRepo
                    .OrdenarResponse(response, 
                                      this.fecha, 
                                      this.medicion, 
                                      this.dia, 
                                      this.mes, 
                                      this.year, 
                                      this.hora,
                                      this.minuto, 
                                      this.Fecha,
                                      this.lineChartData
                    );

                debugger;
              },
              error =>{
                console.log(<any>error);
              }
          );
          }*/

          // lineChart
        public lineChartOptions:any = {
            responsive: true
          };

          public lineChartColors:Array<any> = [
            { // grey
              backgroundColor: 'rgba(148,159,177,0.2)',
              borderColor: 'rgba(148,159,177,1)',
              pointBackgroundColor: 'rgba(148,159,177,1)',
              pointBorderColor: '#fff',
              pointHoverBackgroundColor: '#fff',
              pointHoverBorderColor: 'rgba(148,159,177,0.8)'
            },
            { // dark grey
              backgroundColor: 'rgba(77,83,96,0.2)',
              borderColor: 'rgba(77,83,96,1)',
              pointBackgroundColor: 'rgba(77,83,96,1)',
              pointBorderColor: '#fff',
              pointHoverBackgroundColor: '#fff',
              pointHoverBorderColor: 'rgba(77,83,96,1)'
            },
            { // grey
              backgroundColor: 'rgba(148,159,177,0.2)',
              borderColor: 'rgba(148,159,177,1)',
              pointBackgroundColor: 'rgba(148,159,177,1)',
              pointBorderColor: '#fff',
              pointHoverBackgroundColor: '#fff',
              pointHoverBorderColor: 'rgba(148,159,177,0.8)'
            }
          ];
          public lineChartLegend:boolean = true;
          public lineChartType:string = 'line';

          // events
          public chartClicked(e:any):void {
            console.log(e);
          }

          public chartHovered(e:any):void {
            console.log(e);
          }
    }

....the response always is empty

enter image description here

....this is my database:

enter image description here

enter image description here

Upvotes: 1

Views: 4341

Answers (1)

JeremyW
JeremyW

Reputation: 5272

You are setting up ultimoDia as an observable, and then never subscribing to it. Read up on observables and subscriptions, and you'll understand why your code isn't working. Basically, you are saying "This is the data I will want to listen to" but then you're never actually beginning to listen.

Your mistake is a common one - the AngularFire2 docs are horrible for people unfamiliar with observables/subscriptions. Include a .subscribe() to see your data, something like:

return this.dispositivoRef.valueChanges().subscribe(queriedItems => {
    console.log(queriedItems);
    return queriedItems;
});

*Untested code

Upvotes: 1

Related Questions