изменение значений базы данных ионных источников - PullRequest
0 голосов
/ 05 ноября 2018

я меняю название ключа в базе данных. Сначала у меня есть структура JSON, как это.

"Question1" : {
"rather" : "Go outisde",
"ratherclick" : 6,
"would" : "Stay in home",
"wouldclick" : 6
},

теперь я меняю имя на

"Question5" : {
"answer2" : "Go outisde",
"answer2click" : 6,
"answer1" : "Stay in home",
"answer1click" : 6
},

раньше работал нормально. Функциональность приложения заключается в том, что возникает вопрос, когда пользователь нажимает на вопрос, его показывать процент всех кликов от всех пользовательских кликов. я меняю код, но он не показывает процент, показывает только NAN, который

this .html

<!--
  Generated template for the NewpPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header color="grey">

  <ion-navbar color="grey" center>
        <ion-buttons left>
        <button ion-button icon-only (click)="back()">
          <ion-icon name="md-arrow-back"></ion-icon>
        </button>
          </ion-buttons>

    <ion-title >Would You Rather ?</ion-title>
    <ion-buttons class="bttn" right><button right class="bttn" (click)="presentPrompt()">  <ion-icon color="light" name="md-more"></ion-icon></button></ion-buttons>
  </ion-navbar>

</ion-header>


<ion-content  class="background">

    <ion-slides *ngIf="questions" #slides (ionSlideDidChange)="slideChanged()" class="slidee">



        <ion-slide *ngFor="let question of questions | async; let i = index;" >
           <!--  <div class="orca">
                                      this is for or round 

              </div> -->
            <!-- <h3>Question {{i+1}}</h3> -->
          <div class="quizcontainer" >

          <div class="upperr" text-center (click)="show(question.ckc)" (click)="clickedButton(1,question.answer1)" >
                <p *ngIf="showclicks" style="color: white" item-end class="p11">{{ clickPercentage1 }}% </p>
                <div class="anotherr"><p  class="q1" style="text-align: center;">{{question.answer1}}</p> </div>

          </div>

          <div class="or" style="color: white" ><p class="pp">OR </p></div>


          <div class="down" text-center (click)="show(question.ckc)" (click)="clickedButton(2,question.answer2)" >
                  <p *ngIf="showclicks" style="color: white" item-end class="p1">{{ clickPercentage2 }}% </p>
             <div class="another"> <p  class="q1" >{{question.answer2}}</p></div>
          </div>

          </div>


        </ion-slide>



      </ion-slides>

</ion-content>

this.ts

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ActionSheetController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';
import { AngularFireDatabase } from 'angularfire2/database';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
// import { Storage } from '@ionic/storage';
import * as firebase from 'firebase';
import { Slides } from 'ionic-angular';
import { Home1Page } from '../home1/home1';

import { LocalStorage } from '@ngx-pwa/local-storage';

@IonicPage()
@Component({
  selector: 'page-newp',
  templateUrl: 'newp.html',
})
export class NewpPage {

  @ViewChild('slides') slides: Slides;

    slideOptions: any;
  cli:any;
  showclicks:boolean;
  hideMe: any;
  clickvalue1: number;
  clickvalue2: number;
  clickPercentage1: number;
  clickPercentage2: number;

  answer1clicks: number = 0;
  answer2clicks: number = 0;
  question_str: any;
  item_key: any;
  firebase_flag: boolean;

  questions:Observable<any>;
  wouldquestion : any;
  ratherquestion : any;

  range : number = 0;
  callfor : number = 0;

  constructor(public navCtrl: NavController,private alertCtrl: AlertController, 
    public navParams: NavParams, public actionSheetCtrl: ActionSheetController,  
    public afd: AngularFireDatabase, public http: HttpClient, 
    private localStorage: LocalStorage //public storage: Storage
    ) {

    this.clickvalue1 =  0;
    this.clickvalue2 = 0;
    this.clickPercentage1 = 0;
    this.clickPercentage2 = 0;
    this.answer2clicks = 0;
    this.answer1clicks = 0;
    this.cli = "";
    this.showclicks = false;


  } 

  back(){
this.navCtrl.push(Home1Page)
  }

  slideChanged() {
    let currentIndex = this.slides.getActiveIndex();
    console.log('Current index is', currentIndex);

    // Store value into SharedPreference
    //this.storage.set('indexValue', currentIndex);

    this.localStorage.setItem('indexValue', currentIndex)
      .subscribe(
        (result) => {
          console.log(result);
        }
      );
  }

  goToSlide() {
    this.localStorage.getItem<number>('indexValue')
      .subscribe(
        val => {
          console.log("indexValue : "+val);
          if (val != null) {
            this.range = val;
          }
          this.slides.slideTo(this.range, 0);

          setTimeout( () => {
            this.slides.lockSwipes(true);
          }, 2000);
        }
      )

    // this.storage.get('indexValue').then((val) => {
    //     console.log('Index value', val);
    //     if (val != null) {
    //       this.range = val;
    //     }
    //     this.slides.slideTo(this.range, 500);
    // });
  }
  ionViewDidLoad() {
    console.log('ionViewDidLoad NewpPage');

    this.questions = this.afd.list('Questions').valueChanges();      // <=====  Question is coming from there .
    // this.questions.forEach(item => {
    //   console.log('Item:', item);
    // });

    // this.goToSlide();
    var interval = setInterval(()=>{
      this.goToSlide();

      if (this.callfor == 3) {
        clearInterval(interval);
        this.callfor = 0;
      } else {
        this.callfor = this.callfor + 1;
      }
    },500);
  }

  nextSlide(){
    this.showclicks = false;
        this.slides.lockSwipes(false);
        this.slides.slideNext();
        this.slides.lockSwipes(true);
  }

  presentPrompt() {
  let alert = this.alertCtrl.create({
    title: 'Add Your Question',
    inputs: [
      {
        name: 'would',
        placeholder: 'Would You ',
      },
      {
        name: 'rather',
        placeholder: 'Rather'
      }
    ],
    buttons: [
      {
        text: 'Add',
        role: 'add',
        handler: data => {
          this.wouldquestion = data.would;
          this.ratherquestion = data.rather;
          this.afd.list("Questions/").push({
            answer1:this.wouldquestion,
            answer2:this.ratherquestion,
            answer2click:this.answer2clicks,
            answer1click:this.answer1clicks
          });
        }
      },
          ]
  });
  alert.present();
}




  show(clicks)
  {
    this.showclicks = true;

    if(this.showclicks)
    {
      setTimeout(() => {
        this.nextSlide()
    }, 500);
    }
  }

    clickedButton(index,paramString) 
    {
      this.question_str = paramString

      firebase.database().ref('Questions/').on('value',data => {
         data.forEach( item => 
         {
            if(item.val().answer1 == this.question_str)
            {
              this.item_key = item.key;
              this.firebase_flag = true;
              this.answer1clicks = item.val().answer1click;
              this.answer2clicks = item.val().answer2click;
              this.answer1clicks++;
            }
            else if(item.val().answer2 == this.question_str)
            {
              this.item_key = item.key;
              this.firebase_flag = false;
              this.answer1clicks = item.val().answer1click;
              this.answer2clicks = item.val().answer2click;
              this.answer2clicks++;
            }
         });
    });

    if(this.firebase_flag == true)
    {
    firebase.database().ref('Questions/' + this.item_key).child("answer1click").set(this.answer1clicks);

    }
    else
    {
    firebase.database().ref('Questions/' + this.item_key).child("answer2click").set(this.answer2clicks);

    }
    switch (index) {
      case 1:
        this.clickPercentage1 = Math.round(this.answer1clicks / (this.answer1clicks + this.answer2clicks) * 100);
        this.clickPercentage2 = Math.round(this.answer2clicks / (this.answer1clicks + this.answer2clicks) * 100);
        break;
      case 2:
        this.clickPercentage1 = Math.round(this.answer1clicks / (this.answer1clicks + this.answer2clicks) * 100);
        this.clickPercentage2 = Math.round(this.answer2clicks / (this.answer1clicks + this.answer2clicks) * 100);
        break;
    }
  }

}

работает нормально, пока я просто не изменил значение на. Нажмите «answer1click», скорее нажмите «answer2click», не знаю, покажете ли вы его.

1 Ответ

0 голосов
/ 05 ноября 2018

вы используете строковый тип вместо числа. просто измените его на число, и оно должно работать

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...