【问题标题】:How to execute a function every time an ion-tab button gets clicked每次单击离子标签按钮时如何执行功能
【发布时间】:2019-11-06 16:43:53
【问题描述】:

我正在尝试使用 Ionic 框架构建条形码扫描仪应用程序。 scan.page.ts 中的函数工作正常,但不幸的是只有一次。扫描一个条码后,扫描仪就打不开了。

我认为这可能是离子标签的问题。它们只触发一次 scan() 函数。之后该函数将不再执行。

scan.page.ts

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

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

  productViews: any = {};
  productViewsbyUser: any[] = [];
  isProdcutsAvailable = true;

  selectedProduct: any;
  isCameraOpen = false;
  showScan = false;
  products: any[] = [];
  productFound = true;
  displayUserName: any;

  exitModalDisplayed = false;

  constructor(
    private barcodeScanner: BarcodeScanner,
    private router: Router,
    public platform: Platform,
    private toast: Toast,
    public dataService: DataServiceService,
    public alertCtrl: AlertController) {
    console.log(`Scan Page called`);
    }

  ngOnInit() {

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

    this.scan();

    this.handleBackButton();

  }

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

// Start scanning procedure
  scan() {
    this.selectedProduct = {};
    this.isCameraOpen = true;
    this.showScan = true;
    this.barcodeScanner.scan().then((barcodeData) => {
      setTimeout(() => {
        this.isCameraOpen = false;
      }, 500);
      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.userName = this.displayUserName(); // TO TEST !!!
        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);
        }
      );
    });
  }

  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));

            // ENTER USER NAME HERE???

        });

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

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

  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());
    });
  }
}

tabs.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

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

import { TabsPage } from './tabs.page';

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      { path: 'profile', loadChildren: '../profile/profile.module#ProfilePageModule' },
      { path: 'products', loadChildren: '../products/products.module#ProductsPageModule' },
      { path: 'scan', loadChildren: '../scan/scan.module#ScanPageModule' },
    ]
  },
  {
    path: '',
    redirectTo: '/tabs/products',
    pathMatch: 'full'

  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],
  declarations: [TabsPage]
})
export class TabsPageModule {}

tabs.page.html

<ion-tabs>
    <ion-tab-bar slot="bottom">
      <ion-tab-button tab="products">
        <ion-icon name="md-list"></ion-icon>
        <ion-label>Products</ion-label>
        <!-- <ion-badge>6</ion-badge> -->
      </ion-tab-button>

      <ion-tab-button tab="scan">
        <ion-icon name="md-qr-scanner"></ion-icon>
        <ion-label>Scan</ion-label>
      </ion-tab-button>

      <ion-tab-button tab="profile">
        <ion-icon name="md-person"></ion-icon>
        <ion-label>Profile</ion-label>
      </ion-tab-button>

    </ion-tab-bar>
  </ion-tabs>

我希望每次按下扫描选项卡按钮时都会打开扫描仪。

【问题讨论】:

    标签: javascript angular typescript ionic-framework


    【解决方案1】:

    现在,您的 scan() 函数仅在调用 ngOnInit() 时执行。

    如果您想在用户每次点击选项卡时执行它,您可以执行以下操作:

    <ion-tab-button tab="scan" (click)="scan()">
      <ion-icon name="md-qr-scanner"></ion-icon>
      <ion-label>Scan</ion-label>
    </ion-tab-button>
    

    【讨论】:

    • 感谢您的回答!如何调用该函数? scan() 函数不在 tabs.pages.ts 中,它在 scan.pages.ts 中。或者有没有办法在每次打开scan.page.html时执行该函数?
    • @Valentino 嘿伙计,我建议你把你的函数写在一个服务文件中,这样你就可以在需要的时候调用它。
    • 我不知道这是否是最好的方法,但现在我只是将所有逻辑从 scan.page.ts 移动到 tabs.page.ts 并且它可以工作。谢谢你们的帮助!
    • 我会按照 Eudz 的建议去做。在服务中移动“scan()”函数。然后将服务导入到您需要的组件中。从组件中你可以调用:this.yourNewScanService.scan() 基本上它应该是这样的:angular.io/tutorial/toh-pt4#final-code-review
    猜你喜欢
    • 2022-08-08
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多