我正在尝试从firebase数据库中读取一个值,但我被卡住了。当我尝试对值进行快照时,函数.then()没有被执行。
这是代码。
function checkPublishButton(){
$( "#publish_button" ).click(function(){
//Check if a user is logged in.
firebase.auth().onAuthStateChanged(function(user) {
//Declare firebase data-base
var database = firebase.database();
//Get user's total event created counter
return database.ref("users/" + user.uid ).once('value').then(function(snapshot) {
console.log("This is not executing");
return snapshot.val().total_event_created;
}).then(function(counter) {
//Increase the total_event_counter by one
console.log("This is also not executing");
var counter = counter +1;
database.ref('users/'+user_id+'/total_event_created').set(counter);
//Get input from form
var title = $("#title").val();
var date = $("#date").val();
var hour = $("#hour").val();
var place = $("#place").val();
var brief_description = $("#brief_description").val();
var detailed_description = $("#detailed_description").val();
var contact_email = $("#contact_email").val();
var contact_phone_number = $("#contact_phone_number").val();
var imageUrl = $("#imageUrl").val();
//Post event into firebase database
database.ref('events/' + user_id + '/' + counter).set({
title: title,
date: date,
hour: hour,
place: place,
brief_description: brief_description,
detailed_description: detailed_description,
contact_email: contact_email,
contact_phone_number: contact_phone_number,
imageUrl: imageUrl
});
});
});
});
}
所以,你可以知道这两个代码,因为没有执行console.log()命令。
答案 0 :(得分:0)
呀!代码不起作用。由于您在onAuthStateChanged回调中编写了所有代码,因此只有在身份验证状态发生更改时才会调用。 (用户登录/注销)。在这里,我对你的代码进行了一些重构。希望这对你有帮助。
<?php
class Comments extends CI_Controller{
public function create($post_id){
$post_id = $this->input->post('post_id');
$data['post'] = $this->Posts_model->get_posts($post_id);
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
if($this->form_validation->run()===FALSE){
$this->load->view('templates/header');
$this->load->view('posts/view',$data);
$this->load->view('templates/footer');
}else {
$this->comment_model->create_comment($post_id);
redirect('posts/'.$slug);
}
}
}
?>
**Comment Model**
<?php
class Comment_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function create_comment($post_id = NULL){
$data=array(
'post_id'=>$post_id,
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'body' => $this->input->post('body'),
);
return $this->db->insert('comments',$data);
}
public function get_comments($post_id){
$query = $this->db->get_where('comments',array('post_id'=>$post_id));
return $query->result_array();
}
}