Read data from Firebase Altime databse

Asked

Viewed 848 times

0

I am developing an angular application, and I need to read the recorded data in my firebase database.

inserir a descrição da imagem aqui

How would I read all the data that is inside object 9 for example ? I need to read this data and write it into variables, so I can compare it to other values.

Follow the code of my Komponent.ts:

    import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material';
import { QuestionarioService } from 'src/app/providers/questionario.service';
import { MenuService } from 'src/app/providers/menu.service';
import { FirebaseService } from 'src/app/modules/utils/providers/firebase.service';
import { SessionService } from 'src/app/modules/utils/providers/session.service';
import { Http, Response } from '@angular/http'; 

@Component({
  selector: 'app-questionario',
  templateUrl: './questionario.component.html',
  styleUrls: ['./questionario.component.sass']
})

export class QuestionarioComponent implements OnInit {

 firebase:any;

 valorR:number = 0;
 valorG:number = 0;
 valorB:number = 0;
 valorA:number = 0;
 valorS:number = 0;
 valorI:number = 0;

  constructor(public questionario:QuestionarioService,
  public menu:MenuService,
  public dialog: MatDialog,
  public session: SessionService,
  private http: Http) {
    this.firebase = new FirebaseService();
   }


  ngOnInit() {
  window.scrollTo(0,0);

  let url = ''
  this.http.get( url )
     .pipe( (data: Response) => data.json() ) /* Necessário converter para JSON */
     .subscribe( answers => console.log( answers ) ); 
  }



  getRadioValorR(event){
    if(event.value > this.valorR){
      this.valorR = event.value;
      }
    }


  getRadioValorB(event){
    if(event.value > this.valorB){
      this.valorB = event.value;
    }
  }

  getRadioValorA(event){
    if(event.value > this.valorA){
      this.valorA = event.value;
    }
  }
  getRadioValorS(event){
    if(event.value > this.valorS){
      this.valorS = event.value;
    }
  }

  getRadioValorI(event){
    if(event.value > this.valorI){
      this.valorI = event.value;
    }
  }

  derteminaG(){
    this.valorG = this.valorR;
    if(this.valorG < this.valorB){
      this.valorG = this.valorB;
    }
    if(this.valorG < this.valorA){
      this.valorG = this.valorA;
    }
    if(this.valorG < this.valorS){
      this.valorG = this.valorS;
    }
    if(this.valorG < this.valorI){
      this.valorG = this.valorI;
    }
   return this.valorG;
  }

  getClass0(){
    if(this.derteminaG() == 0){
      return true;
    }

  }
  getClass1(){
    if(this.derteminaG() == 1){
      return true;
    }
  }
  getClass2(){
    if(this.derteminaG() == 2){
      return true;
    }
  }
  getClass3(){
    if(this.derteminaG() == 3){
      return true;
    }
  }

    Desabilitar(element){
    var radio = document.getElementById(element) as HTMLInputElement;
    if(radio.style.display == 'none'){
      radio.style.display = 'table-cell';
    }else radio.style.display = 'none';
  }



}

2 answers

0

Use in your function :

  var key: string;
  return new Promise((resolve, reject) =>{
  return this.db.object("9" + key).snapshotChanges()
  .map(c => {
    return { key: c.key, ...c.payload.val() };
  });
})

0


For this you need to use the angular HTTP module to request your table in firebase and extract the desired value.

First step: import the HTTP module into your app.module.ts

/* app.module.ts*/

import { HttpModule } from '@angular/http';


...

imports[
  ...
  HttpModule      /* Adicionar o HttpModule dentro de imports */
]

Second step: Import HTTP into the component that wants to request and start setup

Read the comments in the code to understand each step

...

import { Http, Response } from '@angular/http'; 
/* Importa o Http e também o tipo Response */

constructor( private http: Http) {} // Adicione o módulo ao seu constructor

ngOnInit() {
     /* O método GET retorna os dados da sua requisição */
     /* Você precisa passar a URL do seu banco de dados no Firebase como parametro*/

     /* As URLs do Firebase geralmente tem esse formato: 
      *  https://nomeprojeto-18e6c.firebaseio.com/recipes.json
      */

    let url = 'https://nomeprojeto-18e6c.firebaseio.com/nomebanco.json'
     this.http.get( url )
     .pipe( (data: Response) => data.json() ) /* Necessário converter para JSON */
     .subscribe( answers => console.log( answers ) ); 

     /* console.log imprimirá sua tabela com os objetos 9, 10, 11*/
}

IMPORTANT INFORMATION IN ITS CONTEXT

Within the subscribe you can assign the returned value to a variable.

I will add a property above the constructor to illustrate what can be done.

...

import { Http } from '@angular/http'; /* Importa o Http */



Answers: any; /* VARIÁVEL NOVA */
constructor( private http: Http) {} // Adicione o módulo ao seu constructor

ngOnInit() {
     /* O método GET retorna os dados da sua requisição */
     /* Você precisa passar a URL do seu banco de dados no Firebase como parametro*/

     /* As URLs do Firebase geralmente tem esse formato: 
      *  https://nomeprojeto-18e6c.firebaseio.com/recipes.json
      */

    let url = 'https://nomeprojeto-18e6c.firebaseio.com/nomebanco.json'
     this.http.get( url )
     .pipe( data => data.json() ) /* Necessário converter para JSON */
     .subscribe( answers => {
         this.answers = answers 
     }); 

     /* console.log imprimirá sua tabela com os objetos 9, 10, 11*/
}
  • If I want to return only object 9 for example, I just change Answers for 9 ?

  • As the return will be an object you can access through the key of the object. In this case, this.answers. 9.

  • The following error was returned after I entered your code : "message": "The json property does not exist in type 'Observable<Response>'.

  • Is not working :/

  • Ok, on the line where you have . pipe( date => data.json() replace with this: . pipe( (date:any) => data.json() ) The correct is to add the type Sponse on return, but I will update the code more calmly soon

  • I replaced it and the error disappeared, but once the page is loaded and the code is called inside ngOnInit(), the application breaks ...

  • This is the error returned : ERROR Error: Uncaught (in Promise): Error: Staticinjectorerror(Appmodule)[Questionariocomponent -> Http]: Staticinjectorerror(Platform: core)[Questionariocomponent -> Http]: Nullinjectorerror: No Provider for Http! Error: Staticinjectorerror(Appmodule)[Questionariocomponent -> Http]: Staticinjectorerror(Platform: core)[Questionariocomponent -> Http]: Nullinjectorerror: No Provider for Http! at Nullinjector.push.. /node_modules/@angular/core/fesm5/core.js.Nullinjector.get

  • Maybe there’s some other logic to your code that conflicts with what I suggested. Ideally you edit your question and add what you have there to make it easier to help.

  • @JVM Ah, there’s one more thing. You need to import the HTTP module inside your App.module.ts I will update the response to make it better to read, okay? Take a look in about 2 minutes.

  • @JVM Code updated. I believe it will now work!

  • Returned an error on top of Response. I’ll update the question q post my code to see if you can help me.

  • I don’t know if the error is only in the example you pasted or in your code, but you need to add your URL and organize the code this way: let url = "SUA URL"&#xA; this.http.get( url ) .pipe( (data: Response) => data.json() ) &#xA; .subscribe( &#xA; answers => console.log( answers ) ); }

  • I’m going to need to get out here now, unfortunately. I hope I’ve helped up to a certain point. I’m realizing that you’re having quite a hard time with basic Angular concepts. I suggest looking for some online course to follow up, it will be more productive for you. Good luck and do not give up!

  • I just took the URL to post the code here, but thank you so much for the help !

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.