无法从Firebase Realtime DB获取数据

时间:2019-11-01 13:34:41

标签: angular typescript firebase ionic-framework firebase-realtime-database

我正在尝试使用Ionic和Firebase构建QR码扫描仪。当我扫描QR码以将plu与Firebase存储的信息相匹配时,该应用会抛出Product not found吐司。不幸的是,我不知道为什么。

我可以从数据库中获取用户和组织数据,但由于某种原因,该数据不适用于产品(plu)扫描器。

我已经尝试过修改home.page.ts中的scan()函数,并在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 :(得分:0)

发现了问题。

我忘记添加:

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