Не удается получить данные из базы данных Firebase Realtime - PullRequest
0 голосов
/ 01 ноября 2019

Я пытаюсь создать сканер QR-кода с Ionic и Firebase. Когда я сканирую QR-код, чтобы сопоставить его с информацией, хранящейся в Firebase, приложение выдает тост Product not found. К сожалению, я не могу понять, почему.

Я могу получить данные пользователя и организации из БД, но почему-то это не работает со сканером продукта (plu).

Я уже пытался изменитьфункция scan () в home.page.ts и воспроизводилась в data-service.service.ts, но не работала.

home.page.ts

import { Component, NgZone } from '@angular/core';
import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';
import { Toast } from '@ionic-native/toast/ngx';
import { DataServiceService } from '../../app/data-service.service';
import { Platform, AlertController, NavController, ModalController } from '@ionic/angular';
import { AuthenticateService } from '../authentication.service';
import { Router, NavigationEnd } from '@angular/router';
import { LoadingController } from '@ionic/angular';
import * as moment from 'moment';


@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  products: any[] = [];
  organizations: any = [];
  productViews: any = {};
  productViewsbyUser: any[] = [];
  selectedProduct: any;
  productFound = true;
  showProductInfo = false;
  showProfile = false;
  showScan = false;
  isProdcutsAvailable = true;
  isCameraOpen = false;
  exitModalDisplayed = false;
  objectKeys = Object.keys;
  userEmail: string;
  userOrganization: any;
  displayUserName: any;
  userWorkTimeList: any = [];

  processingInitApp = false;
  viewApp = true;

  watch: any;
  watchPositionSubscription: any;

  constructor(public navCtrl: NavController,
    private barcodeScanner: BarcodeScanner,
    private toast: Toast,
    private router: Router,
    private authService: AuthenticateService,
    public dataService: DataServiceService,
    public loadingCtrl: LoadingController,
    public alertCtrl: AlertController,
    public modalController: ModalController,
    public zone: NgZone,
    public platform: Platform) {
    console.log(`Home Page called`);
  }

  getMoment() {
    return moment().milliseconds(0);
  }

  // tslint:disable-next-line: use-life-cycle-interface
  ngOnInit() {
    console.log('ngOnInit called');
    this.router.events.subscribe((value) => {
      if (value instanceof NavigationEnd) {
        console.log('come here:', value.url);
        if (value.url === '/home') {
          // this.initApp();
        }
      }
    });

    this.platform.resume.subscribe((e) => {
      // navCtrl.navigateRoot('home');
      // tslint:disable-next-line: no-console
      console.trace('resume called');
      // this.resetShiftData();
      // this.initApp();
    });
    this.handleBackButton();
  }


  initApp() {
    if (this.processingInitApp) {
      return;
    }
    // this.loadingCtrl.create
    this.processingInitApp = true;
    setTimeout(() => {
      this.processingInitApp = false;
    }, 5000);
    // this.resetCurrentUserData();
    }

async initProfileData() {
    if (this.authService.userDetails()) {
      this.userEmail = this.authService.userDetails().email;
    }

    this.dataService.getUserOrganization()
      .subscribe((response) => {
        // this.userOrganization = response;
        console.log('userOrganization response ', response);
        const result = this.organizations.find(obj => {
          return obj.id === response;
        });
        // console.log(result);
        this.userOrganization = result.name;
        console.log('this.userOrganization ', this.userOrganization);
        // console.log(this.organizations.find(x => x.id == this.userOrganization));
      });

    this.dataService.fetchUserName()
      .subscribe((response) => {
        this.displayUserName = response;
        console.log('fetchUserName response ', response);
      });

  }

  async initScanHistoryData() {
    this.dataService.getProductViewsForUser()
      .subscribe((response) => {
        this.productViews = response;
        const userProductViews = [];
        // tslint:disable-next-line: forin
        for (const key in this.productViews) {
          userProductViews.push(this.productViews[key]);
        }
        userProductViews.sort(function (a, b) {
          return moment(b.scannedAt).diff(moment(a.scannedAt));
        });

        this.productViewsbyUser = userProductViews;
        console.log('user productViews ', userProductViews);

        if (this.productViewsbyUser.length) {
          this.isProdcutsAvailable = true;
        } else {
          this.isProdcutsAvailable = false;
        }
        // console.log('productViews ', this.productViews);
      });
  }

  scan() {
    this.selectedProduct = {};
    this.isCameraOpen = true;
    this.showProfile = false;
    this.showProductInfo = false;
    this.showScan = true;
    this.barcodeScanner.scan().then((barcodeData) => {
      setTimeout(() => {
        this.isCameraOpen = false;
      }, 1000);
      if (barcodeData.cancelled) {
        return;
      }
      console.log(`barcodeData`, barcodeData);
      this.selectedProduct = this.products.find(product => product.plu === barcodeData.text);
      if (this.selectedProduct !== undefined) {
        this.selectedProduct.scannedAt = this.getMoment().toISOString();
        // this.selectedProduct.date = newDate;
        this.productFound = true;
        // insert product views with firebase generated based key
        this.dataService.insertProductViewAnalaytics(this.selectedProduct)
          .subscribe(() => {
            console.log(`Product view analytics inserted in Firebase`);
            this.initScanHistoryData();
          });

      } else {
        this.productFound = false;
        this.toast.show(`Product not found`, '5000', 'center').subscribe(
          toast => {
            console.log(toast);
          }
        );
      }
    }, (err) => {
      setTimeout(() => {
        this.isCameraOpen = false;
      }, 1000);
      this.toast.show(err, '5000', 'center').subscribe(
        toast => {
          console.log(toast);
        }
      );
    });
  }

  showProduct() {
    this.loadingCtrl.create({
      message: 'Loading...',
      duration: 1000
    }).then(async (res) => {
      await this.initScanHistoryData();
      res.present();
      this.showProfile = false;
      this.showScan = false;
      this.showProductInfo = true;

      res.onDidDismiss().then((dis) => {
        // console.log('Loading dismissed! after 2 Seconds');
      });
    });

  }

  showProfileInfo() {
    this.loadingCtrl.create({
      message: 'Loading...',
      duration: 1000
    }).then(async (res) => {
      await this.initProfileData();
      res.present();
      this.showProfile = true;
      this.showProductInfo = false;
      this.showScan = false;

      res.onDidDismiss().then((dis) => {
        // console.log('Loading dismissed! after 2 Seconds');
      });
    });
  }

  logout() {
    this.authService.logoutUser()
      .then(async (res) => {
        await this.resetCurrentUserData();
        // this.watchPositionSubscription.unsubscribe();
        this.router.navigateByUrl('/login');
      })
      .catch(error => {
        console.log(error);
      });
  }

  async resetCurrentUserData() {
    this.showProfile = false;
    this.showProductInfo = false;
    this.showScan = false;
    this.productViewsbyUser = [];
    this.userEmail = '';
    this.displayUserName = '';
    this.userOrganization = '';
  }

  handleBackButton() {
    this.platform.backButton.subscribeWithPriority(9999, () => {
      console.log('exit');
      if (this.exitModalDisplayed || this.isCameraOpen) {
        return;
      }
      this.exitModalDisplayed = true;
      const alert = this.alertCtrl.create({
        header: 'Do you want to Exit?',
        // message: 'Do you want Exit?',
        buttons: [
          {
            text: 'Cancel',
            role: 'cancel',
            cssClass: 'secondary',
            handler: () => {
              console.log('Cancel clicked');
              this.exitModalDisplayed = false;
            }
          }, {
            text: 'Yes',
            handler: () => {
              console.log('Confirm Okay');
              navigator['app'].exitApp();
            }
          }
        ]
      });
      alert.then(x => x.present());
    });
  }
}

data-service.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment  } from '../environments/environment';
// import * as firebase from 'firebase/app';


@Injectable({
  providedIn: 'root'
})
export class DataServiceService {
  userId: any;
  userName: any;
  products: any;
  databaseUrl = environment.firebase.databaseURL;
  // authToken = '';

  constructor(private http: HttpClient) {
    console.log('Hello DataServiceService Provider');
    console.log(this.databaseUrl);
    this.userId = localStorage.getItem('userId');
  }

  setUserId(userId: string) {
    console.log('setUserId ');
    this.userId = userId;
    localStorage.setItem('userId', userId);
  }

  getUserId() {
    return this.userId;
  }

  getUserName() {
    return this.userName;
  }

  setUserName(userName) {
    this.userName = userName;
  }

  // createFirebaseId() {
  //   return firebase.database().ref('/dummy').push().key;
  // }

  getProducts() {
    return this.http.get(`${this.databaseUrl}/products/.json`);
  }

  getOrganizations() {
    return this.http.get(`${this.databaseUrl}/organizations/.json`);
  }

  insertUser(data) {
    return this.http.put(`${this.databaseUrl}/users/${data.uId}.json`, data);
  }

  // an API to insert product views with firebase generated key
  insertProductViewAnalaytics(data) {
    return this.http.post(`${this.databaseUrl}/users/${this.userId}/product_views.json`, data);
  }

  getProductViewsForUser() {
    return this.http.get(`${this.databaseUrl}/users/${this.userId}/product_views/.json`);
  }

  getUserOrganization() {
    return this.http.get(`${this.databaseUrl}/users/${this.userId}/organization/.json`);
  }

  fetchUserName() {
    return this.http.get(`${this.databaseUrl}/users/${this.userId}/userName/.json`);
  }

  // an API to insert product views with custom timestamp based key
  insertProductViewAnalayticsTimestamp(data) {
    // tslint:disable-next-line: max-line-length
    return this.http.put(`${this.databaseUrl}/product_views_timestamp/${data.scannedAt}.json`, data);
  }

}

Структура Firebase: Firebase structure

Приложение Ionic должно отсканировать код и показать соответствующую информацию, которая хранится вБД Firebase.

1 Ответ

0 голосов
/ 01 ноября 2019

Найдена проблема.

Я забыл добавить:

this.dataService.getProducts()
    .subscribe((response) => {
      this.products = <any[]><unknown>response;
      console.log(this.products);

...