Mohammed Hadi
Mohammed Hadi

Reputation: 65

get the random key from firebase database in ionic 4

I'm trying to get the random key that is generated when I add data under "Course" to Firebase. I'm using ionic 4 for my application.

[1] https://i.sstatic.net/xq7GL.jpg

in the code bellow, inside the onSubmit function, the last two lines: i had one variable that holds the the UID of the user called "currentUser", and another variable that should hold the key of the data added "datakey". I'm not sure what should be the complete code for the "dataKey" variable so that I can get the key of the data added.

Any help ?

import { Component, OnInit } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { Validators, FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { FirebaseService } from '../services/firebase.service';
import { AuthService } from '../services/auth.service';

import { AngularFirestore } from '@angular/fire/firestore';
import * as firebase from 'firebase/app';

import { LoadingController } from '@ionic/angular';

@Component({
    selector: 'app-subjects',
    templateUrl: './subjects.page.html',
    styleUrls: ['./subjects.page.scss'],
})
export class SubjectsPage implements OnInit {

    subject_form: FormGroup;
    subjects: Array<any>;
    gradeArray: number[]=[];
    creditHourArray: number[]=[];
    creditHourTot: number=0;
    gpaDisplay: number;
    dataKey: string;


    constructor(
        private authService: AuthService,
        private formBuilder: FormBuilder,
        private firebaseService: FirebaseService,
        private router: Router,
        private route: ActivatedRoute,
        public loadingCtrl: LoadingController,
        public afs: AngularFirestore,

    ) { }
    ngOnInit() {
        if (this.route && this.route.data) {
            this.getData();
          }
          this.resetFields();

        }

        async getData(){
                this.route.data.subscribe(routeData => {
                  routeData['data'].subscribe(data => {
                    this.subjects = data;
                  })
                })
              }

              async presentLoading(loading) {
                return await loading.present();
              }

    resetFields() {
        this.subject_form = this.formBuilder.group({
            subName: new FormControl('', Validators.required),
            subCode: new FormControl('', Validators.required),
            creditHour: new FormControl('', Validators.required),
            grade: new FormControl('', Validators.required)
        });
    }

    onSubmit(value) {

        this.gradeArray.push(value.grade)
        this.creditHourArray.push(value.creditHour)
        let data = {
            subName: value.subName,
            subCode: value.subCode,
            creditHour: value.creditHour,
            grade: value.grade,
        }


        this.creditHourTot= this.creditHourTot + value.creditHour;




        this.firebaseService.createSubjects(data,this.gradeArray,this.creditHourArray)
        this.firebaseService.createGPA(this.gradeArray,this.creditHourArray)
        this.gpaDisplay = this.firebaseService.calGPA(this.gradeArray,this.creditHourArray)
        console.log(this.gpaDisplay);

        let currentUser = firebase.auth().currentUser
        let dataKey = this.afs.collection('people').doc(currentUser.uid).collection('Course')

    }

    goToSemPage() {
        this.router.navigate(["/semesters"]);
    }

    goToSubListPage(){
      this.router.navigate(["/subject-list"]);
    }


    logout() {
        this.authService.doLogout()
            .then(res => {
                this.router.navigate(["/home"]);
            }, err => {
                console.log(err);
            })
    }
}

this is the code of my method "createSubjects"

  createSubjects(value,gradeArray,creditHourArray) {
    return new Promise<any>((resolve, reject) => {

      let currentUser = firebase.auth().currentUser; 

      this.afs.collection('people').doc(currentUser.uid).collection('Course').add({
        subName: value.subName,
        subCode: value.subCode,
        creditHour: value.creditHour,
        grade: value.grade
        gpa: this.calGPA(gradeArray,creditHourArray)
      })

      .then(
          res => resolve(res),
          err => reject(err)
      )

    })
  }

UPDATE: The new "onSubmit" method:

onSubmit(value) {

        this.gradeArray.push(value.grade)
        this.creditHourArray.push(value.creditHour)
        let data = {
            subName: value.subName,
            subCode: value.subCode,
            creditHour: value.creditHour,
            grade: value.grade,
        }


        this.creditHourTot= this.creditHourTot + value.creditHour;

        this.firebaseService.createSubjects(data,this.gradeArray,this.creditHourArray).then(
            (val) => { this.datakey = val.id }
        );
        this.firebaseService.createGPA(this.gradeArray,this.creditHourArray)
        this.gpaDisplay = this.firebaseService.calGPA(this.gradeArray,this.creditHourArray)

        console.log(val);

        // let currentUser = firebase.auth().currentUser
        // let datakey = this.afs.collection('people').doc(currentUser.uid).collection('Course')

    }

Upvotes: 0

Views: 826

Answers (1)

Raphael St
Raphael St

Reputation: 671

I am not entirely sure of my understanding of your use-case.

I assume your method "createSubjects" is the one in which you make your calls to firebase to create "Course".

So you need to return a promise in your method "createSubject",

if createSubject returns directly a firebase promise then you just need to:

this.firebaseService.createSubjects(data,this.gradeArray,this.creditHourArray).then(
    (val) => { this.datakey = val.id }
);

edit: I changed 'key' to 'id' , key is what you get on firebase, on firestore 'id' is used.

Upvotes: 1

Related Questions