ionic-team / ionic-framework

A powerful cross-platform UI toolkit for building native-quality iOS, Android, and Progressive Web Apps with HTML, CSS, and JavaScript.
https://ionicframework.com
MIT License
51.02k stars 13.51k forks source link

bug: impossible to use the back Button ion ionic application #28275

Closed aragon5956 closed 1 year ago

aragon5956 commented 1 year ago

Prerequisites

Ionic Framework Version

v7.x

Current Behavior

hello , my back button on android application doesn't work why ? this is my code


import {
  AfterViewInit,
  ChangeDetectorRef,
  Component,
  ElementRef,
  OnInit,
  QueryList,
  ViewChild,
  ViewChildren
} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {PhotoService} from '../services/photo/photo.service';
import {UserCrudService} from '../services/user/user-crud.service';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
import {GetPriceService} from '../services/getprice/get-price-service';
import {registerLocaleData} from "@angular/common";
import localeFr from '@angular/common/locales/fr';
import {User} from "../services/user/user";
import {Platform, ToastController} from "@ionic/angular";

@Component({
  selector: 'app-payer-note-de-frais',
  templateUrl: './payer-note-de-frais.page.html',
  styleUrls: ['./payer-note-de-frais.page.scss'],
})
export class PayerNoteDeFraisPage implements OnInit, AfterViewInit {
  @ViewChild('prixUnite') prixUnite: ElementRef;
  @ViewChild('nbUnite') nbUnite: ElementRef;
  @ViewChild('leSelect') leSelect: ElementRef;
  @ViewChild('TableauNoteDeFrais') tableauNoteDeFrais: ElementRef;
  @ViewChildren('presenceInput') presenceInputClass: QueryList<ElementRef>;

  private username: string;
  nombrePhotos: any;
  public _noteDeFrais = [];
  mesDates: any[] = [];
  priceInput: number[] = [];
  presenceInput: number[][];
  uneDate: Date = new Date();
  private _place: any;
  private _options: any;
  noteDeFraisForm: any;
  private monUser: User;
  private totalPresencesMois: number;
  private backButtonSubscription: Subscription;

  constructor(
    private toastController: ToastController,
    private getPrice: GetPriceService,
    private monUserService: UserCrudService,
    private router: Router,
    private _photoService: PhotoService,
    private route: ActivatedRoute,
    private screenOrientation: ScreenOrientation,
    private cdRef: ChangeDetectorRef,
    private platform: Platform
  ) {
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE);
    this.presenceInput = [];
  }

  ngOnInit() {
    registerLocaleData(localeFr);
    this.checkLoginStatus();

    try {
      const parameters = JSON.parse(this.route.snapshot.params.param);
      this.username = parameters.username;
      for (let dateStr of parameters.dates) {
        this.mesDates.push(new Date(dateStr));
      }
    } catch (error) {
      console.error("Erreur lors de la récupération des paramètres:", error);
    }
    try {
      this.initTableau(this.presenceInput);
    } catch (error: any) {
      console.error(error.toString());
    }
    try {
      this.getJourDePresencesTableau(this.presenceInput);
    } catch (error: any) {
      console.error(error.toString());
    }
    try {
      this.initialiserPremierTableauNoteDeFrais()
    } catch (error: any) {
      console.error(error.toString());
    }

  }
  initializeBackButtonCustomHandler(): void {
    this.backButtonSubscription = this.platform.backButton.subscribeWithPriority(999999, () => {
      this.router.navigate(['accueil']);
    });
  }

  mettreAJourFonction() {
    this.cdRef.detectChanges();
    this.mettreAJourProduit();
  }

  ngAfterViewInit() {
    if (this.username) {
      if (this.uneDate) {
        try {
          this.presenceInputClass.changes.subscribe(() => {
            console.log(this.presenceInputClass.length);
            Promise.resolve().then(() => this.mettreAJourProduit());
          });
        }
        catch(error :any){
          console.error(error);
        }
      }
    }
  }

  ngOnDestroy(): void {
    this.screenOrientation.unlock();
    this.platform.backButton.unsubscribe();
      if (this.backButtonSubscription && !this.backButtonSubscription.closed) {
      this.backButtonSubscription.unsubscribe();
  }

  private checkLoginStatus(): void {
    if (localStorage.getItem('token') == null && localStorage.getItem('username') == null) {
      this.router.navigate(['login']);
    }
  }

  initialiserPremierTableauNoteDeFrais() {
    try {
      this.monUserService.getUserByUsername(this.username).subscribe(monUser => {
        try {
          this.getPrice.getPrixParTypeDeNoteDeFraisByName(monUser.username)
            .subscribe(
              data => {
                this._noteDeFrais = data.map(item => ({
                  name: item.name,
                  value: item.value
                }));
                const elementsArrayNumbers = document.getElementsByClassName('SecondTablePrice');
                Array.prototype.forEach.call(elementsArrayNumbers, (el, index) => {
                  const selectedItem = this._noteDeFrais.find(item => item.name === this.leSelect.nativeElement.value);
                  if (selectedItem) {

                    el.value = selectedItem.value;
                    el.setAttribute('disabled', true);
                  } else {
                    console.log(`No item found for select value: ${this.leSelect.nativeElement.value}`);
                  }

                });
              },
              error => {
                console.log('An error occurred: ', error);
              }
            );
        } catch (error: any) {
          console.error(error);
        }
        /*try{
          this.mettreAJourProduit();
        }
        catch (error:any){
          console.error(error);
        }*/
      });
    }
    catch (error :any){
      console.error(error);
    }
  }

  filtrerParNom(nom: string): void {
    const elementsArrayNumbers = document.getElementsByClassName('SecondTableNumber');
    const elementsArrayItems = document.getElementsByClassName('SecondTablePrice');
    const selectedItem = this._noteDeFrais.find(item => item.name === nom);
    this.getJourDePresencesTableau(this.presenceInput);
    if (selectedItem) {
      //on doit trouver un moyen de parcourir les cellules pour mettre les tableaux
      Array.prototype.forEach.call(elementsArrayItems, (el, index) => {
        el.value = selectedItem.value;
        el.setAttribute('disabled', 'true');
      });
      Array.prototype.forEach.call(elementsArrayNumbers, (el, index) => {
        el.value = this.getSecondDimensionSum(index);
        el.setAttribute('disabled', 'true');
      });
    } else {
      console.log(`No item found for select value: ${nom}`);
    }

  }

  private getSecondDimensionSum(index: number): number {
    let sum = 0;
    for (let j = 0; j < this.presenceInput[index].length; j++) {
      console.log(this.presenceInput[index][j]);
      sum += this.presenceInput[index][j];
      console.log(sum);
    }
    return sum;
  }

  takePhoto() {
    this._photoService.addNewToGallery(this.nombrePhotos);
  }

  getJourDePresencesTableau(mesJoursDePresence: number[][]): void {
    const user: User = new User();
    for (const uneDate of this.mesDates) {
      console.log(uneDate.toString());
      try {
        this.monUserService.getDaysPresences(this.username, uneDate.getMonth(), uneDate.getFullYear()).subscribe(res => {
          mesJoursDePresence = res
          this.presenceInput = res;
          console.log(mesJoursDePresence);
        });
      } catch (error: any) {
        console.error(error.toString());
      }
    }
  }
  mettreAJourProduit(): void {
    const totalSomme = this.sommePresence(this.presenceInput);
    const inputArray = this.presenceInputClass.toArray();  // Transformation en tableau

    console.log("la longueur du tableau this.presenceInputClass " + inputArray.length);
    console.log(inputArray);
    try {
      inputArray.forEach((elRef, index) => {
        const el = elRef;  // Accéder directement à la propriété el
        console.log(elRef['el'].value);
      if (el) {
          // ou el.toString() si vous voulez le convertir en string
          const produit = this._noteDeFrais[index].value * totalSomme;
          console.log('produit pour l’index ' + index + ' vaut ' + produit);
          this._noteDeFrais[index].produit = produit;
          elRef['el'].value = this._noteDeFrais[index].produit;
          elRef['el'].setAttribute('disabled', 'true');
        } else {
          console.warn(`el pour l'index ${index} est indéfini.`);
        }
      });
    }catch (error: any) {
      console.error(error);
    }
  }
  sommePresenceDeux(presences: number[][]): number {
    return presences.reduce((acc, val) => acc + val.reduce((a, v) => a + v, 0), 0);
  }

  sommePresence(monTableau:number[][]): number {
    let somme = 0;
    for (let i = 0; i < monTableau.length; i++) {
      for (let j = 0; j < monTableau[i].length; j++) {
        if (monTableau[i][j] === 1) {
          somme += 1;
        }
      }
    }
    return somme;
  }

  getProductNUmberAndPrice(): any {
    let sommePrices = 0;
    let sommeNumber = 0;
    const elements = document.getElementsByClassName('SecondTablePrice');
    Array.prototype.forEach.call(elements, function(el) {
      const valeurTempo = Number(el.value);
      sommePrices += valeurTempo;
      console.log(valeurTempo);
      console.log(sommePrices);
    });
    const elementsArrayNumbers = document.getElementsByClassName('SecondTableNumber');
    Array.prototype.forEach.call(this.presenceInput, function(el) {
      const valeurTempoDeux = Number(el.value);
      sommeNumber += Number(valeurTempoDeux);
      console.log(valeurTempoDeux);
      console.log(sommeNumber);
    });
    return Number(sommeNumber) * Number(sommePrices);
  }

  soumettre() {
    //const parameters=this.route.snapshot.params.jsonParametres
    const variable: number = this.getProductNUmberAndPrice();
    this.monUserService.createDirectory(this.username + '/' + this.mesDates.toString() + '/');

    let param: any={
      somme: variable,
      username: this.username,
      date : new Date(this.route.snapshot.params.uneDate)
    };
    param = JSON.stringify(param);
    this.router.navigate(['/signature', {param}]);
  }

  allerPagePresence() {
    let param: any = {
      username: this.username,
      selectedDates: this.mesDates
    };
    param = JSON.stringify(param);
    this.router.navigate(['/presence', {param}]);
  }

   initTableau(monTableau: number[][]){
    for (let i = 0; i < 6; i++) {
      monTableau[i]=[];
      for (let j = 0; j < 5; j++) {
        monTableau[i][j] = 0;
      }
    }
  }
  get photoService(): PhotoService {
    return this._photoService;
  }

  set photoService(value: PhotoService) {
    this._photoService = value;
  }

  get place(): any {
    return this._place;
  }

  set place(value: any) {
    this._place = value;
  }

  get options(): any {
    return this._options;
  }

  set options(value: any) {
    this._options = value;
  }
  getValuesFirstTable(): number {
    return this.prixUnite.nativeElement.value * this.nbUnite.nativeElement.value;
  }

  getTotalFees(): any {
    let produit=0 ;
   this._noteDeFrais.forEach(item=>{
    produit += item.produit;

   });
    return produit;
  }

async presentToast() {
    const toast = await this.toastController.create({
      message: 'Veuillez entrer un nombre de photos supérieur à 0.',
      duration: 2000
    });
    toast.present();
  }
}

Expected Behavior

the back button close immediately the application

Steps to Reproduce

  1. chat gtp 4
  2. documentation internet

Code Reproduction URL

No response

Ionic Info

lastest version existed

Additional Information

nothing

liamdebeasi commented 1 year ago

Hi there,

We use this bug tracker exclusively for bug reports or feature requests. This is more of a support question, so I encourage you to ask this question on the Ionic Forums. If after debugging you've determined that this behavior may be due to a bug in Ionic, please feel free to open a new issue.

As for examples on how to use ion-back-button, we have playground examples on https://ionicframework.com/docs/api/back-button. You can also try the "list" Ionic starter application on https://ionicframework.com/start#basics for another working example.

Thanks!

aragon5956 commented 1 year ago

yes but 'i can't use the hardware button ?

liamdebeasi commented 1 year ago

Ionic supports the hardware back button: https://ionicframework.com/docs/developing/hardware-back-button

Note that if you are using Capacitor you need to have the @capacitor/app package installed.

ionitron-bot[bot] commented 11 months ago

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Ionic, please create a new issue and ensure the template is fully filled out.