-
Conteúdo Similar
-
Por Ted2370
Estou buscando aprender sobre o real-time-database do firebase, e de inicio estou tentando dar um push de 2 inputs pro meu banco de dados, mas quando clico no botao, nada acontece :( .
Erro-Console:
Uncaught ReferenceError: firebase is not defined at real-time-database.js:14 app.js:
const firebaseConfig = { apiKey: "AIzaSyAz6JIkeQ6rH1gXTPIsTR24ce2nlLDUQcE", authDomain: "curso-fb-2d7d0.firebaseapp.com", databaseURL: "https://curso-fb-2d7d0.firebaseio.com", projectId: "curso-fb-2d7d0", storageBucket: "curso-fb-2d7d0.appspot.com", messagingSenderId: "198229858892", appId: "1:198229858892:web:aff0435d35f24210f432e9", measurementId: "G-YRW39NLBWM" }; firebase.initializeApp(firebaseConfig); firebase.analytics(); real-time-database.js
var nameInput = window.document.getElementById("nameInput"); var ageInput = window.document.getElementById("ageInput"); var addButton = window.document.getElementById("addButton"); //Ao clicar no botão addButton.addEventListener('click', function(){ create(nameInput.value, ageInput.value) }); function create(name, age){ var data = { name: name, age: age }; return firebase.database().ref().child('users').push(data); } Index.html
<!DOCTYPE html> <html lang="pt-BR"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta http-equiv="Content-Type" content="text/html"> <title>Aula FireBase</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <h1>Bem Vindo ao FireBase</h1> <ul> <li><a href="real-time-database.html">Real Time Database</a></li> </ul> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <script src="https://www.gstatic.com/firebasejs/7.3.0/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/7.3.0/firebase-analytics.js"></script> <script src="js/app.js"></script> </body> </html> real-time-database.html
<!DOCTYPE html> <html lang="pt-BR"> <head> <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script> <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> <link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta http-equiv="Content-Type" content="text/html"> <title>Aula FireBase</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <h1>Real Time Database</h1> <ul id="usersList"></ul> <div class="cool-md-4"> <form> <div class="form-group"> <label for="nameInput">Nome</label> <input type="text" class="form-control" id="nameInput" placeholder="Nome"> </div> <div class="form-group"> <label for="ageInput">Idade</label> <input type="number" class="form-control" id="ageInput" placeholder="Idade"> </div> <button class="btn btn-lg btn-block btn-primary" id="addButton">Adcionar</button> </form> </div> <br><br> <a href="index.html">Voltar para Home</a> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <script src="js/real-time-database.js "></script> <script src="https://www.gstatic.com/firebasejs/7.3.0/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/7.3.0/firebase-analytics.js"></script> <script src="js/app.js"></script> </body> </html> package.json
{ "name": "curso-fb", "version": "1.0.0", "description": "", "main": "index.js", "dependencies": { "jquery": "^3.4.1", "bootstrap": "^4.3.1" }, "devDependencies": {}, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" }
-
Por AlvacirJunior
Boa tarde pessoal, sou novo no fórum e também em javascript, mas vou tentar ser o mais breve possível.
Eu tenho uma função que me retorna um array, essa função é chamada no construtor do meu service onde é atribuído a outra variável, assim:
getValor(){ const key: string = this.afAuth.auth.currentUser.uid; const PATH: string = 'usuarios/'; let fbRef: any; fbRef = this.db.database.ref(PATH + key); var getListings = function () { var currentItems =[]; var currentUser = []; fbRef.on("value", function(snapshot) { currentItems.push(snapshot.val()); currentUser.push({ nome: currentItems[0].nome, celular: currentItems[0].celular, email: currentItems[0].email, idPerfil: currentItems[0].idPerfil, photoURL: null, emailVerificado: currentItems[0].emailVerificado }); }),function (errorObject) { console.log("The read failed: " + errorObject.code); }; return currentUser; }; return getListings(); } Essa função getValor() é chamada no construtor do meu service, dessa forma:
constructor( public: blablablalba... ) { this.afAuth.authState.subscribe(user => { if (user) { this.userData = user; this.userDataAuth.push(this.getValor()); this.userDataAuth.map(item => { console.log(item.nome); } console.log('Data', this.userDataAuth[0]); //for (var key in this.dataU) { // console.log(this.dataU[key][key]); //} . . . . Obs: Esse log retorna undefined \/ console.log('Data', this.dataU[0].nome); Enquanto esse retorna a lista de objetos \/ console.log('Data', this.dataU[0]);
-
Por adrianoasg
Boa tarde....
Estou trabalhando em meu TCC e estou desenvolvendo uma app de controle de pedidos no Android Studio usando Java e Firetore, estou com uma dúvida sobre como pegar os dados de um produto na ao clicar na RecycleView, consigo pegar a posição e ID do produto no Firestore.
Classe Adapter:
public class ProductAdapter extends FirestoreRecyclerAdapter<Product, ProductAdapter.ProductHolder> { private OnItemClickListener listener; public ProductAdapter(@NonNull FirestoreRecyclerOptions<Product> options) { super(options); } @Override protected void onBindViewHolder(@NonNull ProductHolder holder, int position, @NonNull Product model) { holder.mTextDescription.setText(model.getDescription()); holder.mTextMeasure.setText(model.getMeasure()); holder.mTextWeight.setText(String.valueOf(model.getWeight())); holder.mTextQuantity.setText(String.valueOf(model.getQuantity())); holder.mTextSalePrice.setText(String.valueOf(model.getSalePrice())); holder.mTextExpirationDate.setText(model.getExpirationDate()); } @NonNull @Override public ProductHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_product_list, viewGroup, false); return new ProductHolder(view); } class ProductHolder extends RecyclerView.ViewHolder { TextView mTextDescription; TextView mTextMeasure; TextView mTextWeight; TextView mTextQuantity; TextView mTextSalePrice; TextView mTextExpirationDate; public ProductHolder(@NonNull View itemView) { super(itemView); this.mTextDescription = itemView.findViewById(R.id.textView_product_description); this.mTextMeasure = itemView.findViewById(R.id.textView_product_measure); this.mTextWeight = itemView.findViewById(R.id.textView_product_weight); this.mTextQuantity = itemView.findViewById(R.id.textView_product_quantity); this.mTextSalePrice = itemView.findViewById(R.id.textView_product_salePrice); this.mTextExpirationDate = itemView.findViewById(R.id.textView_product_expirationDate); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION && listener != null) { listener.onItemClick(getSnapshots().getSnapshot(position), position); } } }); } } public interface OnItemClickListener { void onItemClick(DocumentSnapshot documentSnapshot, int position); } public void setOnItemClickListener(OnItemClickListener listener) { this.listener = listener; } } E a Activity que lista os itens na RecycleView:
public class ProductListActivity extends AppCompatActivity { //firestore instance private FirebaseFirestore db = ConfigurationFirebase.getFirebaseFirestore(); private CollectionReference productRef = db.collection("products"); private static final String TAG = "ProductListActivity"; private ProductAdapter productAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_product); setUpRecycleView(); } private void setUpRecycleView() { Query query = productRef.orderBy("description", Query.Direction.ASCENDING); FirestoreRecyclerOptions<Product> optionsProduct = new FirestoreRecyclerOptions.Builder<Product>() .setQuery(query, Product.class) .build(); productAdapter = new ProductAdapter(optionsProduct); RecyclerView recyclerView = findViewById(R.id.recycler_view_listProducts); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(productAdapter); productAdapter.setOnItemClickListener(new ProductAdapter.OnItemClickListener() { @Override public void onItemClick(DocumentSnapshot documentSnapshot, int position) { Product product = documentSnapshot.toObject(Product.class); String id = documentSnapshot.getId(); String path = documentSnapshot.getReference().getPath(); // DocumentReference docRef = db.collection("products").document(id); // docRef.update("description", "Pastel de Queijo"); Toast.makeText(ProductListActivity.this, "Position: " + position + "ID: " + id, Toast.LENGTH_SHORT).show(); openProductDetails(); } }); } @Override protected void onStart() { super.onStart(); productAdapter.startListening(); } @Override protected void onStop() { super.onStop(); productAdapter.stopListening(); } public void openProductDetails() { Intent intent = new Intent(ProductListActivity.this, ProductDetailsActivity.class); startActivity(intent); finish(); } } -
Por wilkens.gomes@hotmail.com
Como faço para programar uma função para executar uma tarefa em uma determinada hora mesmo se o meu aplicativo web não estiver aberto.
Ex: comparar valor da hora adicionada no banco de dados (database) com a hora local e mudar um dado no (database).
var statusHora = firebase.database().ref('/Hora'); var d = new Date(); var dados = 'Aberto'; var h = ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2); statusHora.on('value', function (snapshot) { if (snapshot.val() == h) firebase.database().ref().child('/Status').set(dados);
-
Por reinaldo054
Eu estou criando um aplicativo em que embaixo do conteúdo da página eu tenho a opção do usuário fazer um comentário. Estou usando o firebase para fazer cadastro e login e já até consegui gravar a mensagem no banco de dados, mas só ela, precisava colocar o nome do usuário ou username, e a data que o comentário foi feito.
------------------ Meu html está assim:
<ion-content #content id="content"> <ion-card *ngFor="let message of messages"> <ion-card-header> {{message.nome}} </ion-card-header> <ion-card-content> {{message.mensagem}} </ion-card-content> <ion-footer> <ion-toolbar> <ion-input placeholder="Comente algo..." [(ngModel)]="message"></ion-input> <ion-buttons end> <button ion-button icon-right (click)="sendMessage()"> Enviar <ion-icon name="send"></ion-icon> </button> </ion-buttons>
--------------------------meu ts está assim:
export class Cap1SegObsPage { @ViewChild("content") content: any; username: string message: string = "" messages = []; constructor(public navCtrl: NavController) { this.getMessages(); } getMessages(){ var messagesRef = firebase.database().ref().child("mensSegObsCap1"); messagesRef.on("value", (snap) => { var data = snap.val(); this.messages = []; for(var key in data){ this.messages.push(data[key]); } this.scrollToBottom(); }); } scrollToBottom(){ var contentEnd = document.getElementById("content-end").offsetTop; this.content.scrollTo(0, contentEnd, 300); } sendMessage(){ var messagesRef = firebase.database().ref().child("mensSegObsCap1"); messagesRef.push({mensagem: this.message, nome: this.username}); this.message = ""; } }
-