What is the best way to incorporate a TypeScript function within a JQuery function?

I'm facing an issue with installing the Angular Instascan library, so I am using it without installing and only importing the script. In order to make it work, I have to use JQuery in my TypeScript file within the component. Is there a way to call a TypeScript function inside a JQuery function to send the QR's content to my web service? I have tried using Ajax to send the data directly to the web service but it is not working.

The QR's function is "escanearQR" and the function that I want to call is "registrarAsistencia" inside the scanner.addListener.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DatosService } from '../datos.service';
import Swal from 'sweetalert2';

declare var $: any;
declare var Instascan: any;

@Component({
  selector: 'app-toma-asistencia',
  templateUrl: './toma-asistencia.component.html',
  styleUrls: ['./toma-asistencia.component.css']
})

export class TomaAsistenciaComponent implements OnInit {

  constructor(private router: Router, public datos: DatosService) { }
  id_actividad_activa: string;
  id_evento_activo: string;
  actividad: any;
  participantes: any;
  qr:string;
  datosEscaner:string;

  obtenerParticipantes() {
    this.datos.getParticipantes(this.id_evento_activo, this.id_actividad_activa).subscribe(res => {
      this.participantes = res;
    }, error => {
      Swal.fire({
        icon: 'error',
        title: '¡Ups!',
        text: 'No hay participantes aún',
        timer: 2000
      });
    });
  }

  escanearQR(){
    $('#btnqr').empty();
    let scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5, mirror: false });
                    scanner.addListener('scan', function(content){
            console.log(content);
            $('#codigoQR').val(content);
            //CALL HERE registrarAsistencia WITH content VALUE
                    });
                    Instascan.Camera.getCameras().then(function (cameras){
                        if(cameras.length > 0){
                            scanner.start(cameras[0]);
                            $('[name="options"]').on('change',function(){
                                if($(this).val() == 1){
                                    if(cameras[0] != ""){
                                        scanner.start(cameras[0]);
                                    }else{
                                        alert('No se ha encontrado camara frontal');
                                    }
                                }else if($(this).val() == 2){
                                    if(cameras[1] != ""){
                                        scanner.start(cameras[1]);
                                    }else{
                                        alert('No se ha encontrado camara trasera');
                                    }
                                }
                            });
                        }else{
                            console.error('No se han encontrado camaras.');
                            alert('No se han encontrado camaras.');
                        }
                    }).catch(function(e){
                        console.error(e);
                        alert(e);
                    });
          
  }

  registrarAsistencia(){

  }

  cerrarEscaner(){
    window.location.reload();
  }

  ngOnInit(): void {
    this.id_actividad_activa = this.datos.getActividadActiva().id_ac;
    this.id_evento_activo = this.datos.getEventoActivo().id_evento;
    this.actividad = this.datos.getActividadActiva().nombre;
    this.obtenerParticipantes();
  }
}

Answer №1

The issue you're encountering is not Angular-related, but rather pertains to the "this" scope within JavaScript functions.

Let's go back to basics: functions declared with the traditional function keyword have a tendency to forget things. This means that they don't retain the value of this at the time of declaration; instead, they utilize the value of this in the context where they are executed.

Arrow Functions (or lambda functions if you're familiar with Java) offer more robust functionality: they are able to remember the intended scope of their declaration as the value of this. In some ways, the following examples achieve the same outcome:

const boundFn = (function() {}).bind(this);
const arrowFn = () => {};

Based on your code snippet, it seems like you're doing something along the lines of

$(this).val();

This indicates that this should be used as the execution context by jQuery. How can you resolve this? Well, it's quite simple if you understand what closures are and recognize that every function in JavaScript is a closure. Declare a constant prior to the scanner variable: it will store the value of this as the instance of the component you're in, or even better, the function within your component:

For a deeper understanding of the solution, we recommend carefully reading this link - javascript.info / closures. Javascript.info serves as a valuable resource for developers looking to grasp the intricacies of JavaScript. Remember: TypeScript is just an extension of JavaScript, so a solid foundation in the latter is essential for effective coding in the former.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

Learn how to showcase a predetermined option in an HTML select element using Vue.js and Minimalect

I am currently utilizing Vue.js along with the Mininmalect HTML select plugin to showcase a list of countries by their names and values, where the value represents the 2 digit country code. Successfully, I have managed to implement the plugin for selectin ...

What is the best way to randomly display an image from a JavaScript array within an HTML document?

I currently have this code in my HTML and JavaScript files, but I am having trouble with displaying images without using a URL in the JavaScript file. The images are located in my project folder. However, when I open the HTML file, the images do not appear ...

Determine the viral coefficient based on the sharing platform being used, whether it is Facebook or Twitter

Traditionally, the viral coefficient is measured through email addresses. For example, if a current user [email protected] invites 10 people via email, you can track how many signed up and calculate the viral coefficient based on that. But what if th ...

Angular error: Attempting to access the value property of an undefined object

When attempting to delete a row from a table, an error occurred stating "TypeError: Cannot read property 'value' of undefined" after placing the delete button at the end of a row. I watched this video tutorial for guidance on deleting a row witho ...

Compiler is unable to comprehend the conditional return type

I've done some searching, but unfortunately haven't been able to find a definitive solution to my issue. Apologies if this has already been asked before, I would appreciate any guidance you can offer. The problem I'm facing involves a store ...

The disappearing background of a div is causing a ripple effect on the other divs layered on top of the

I'm facing an issue with my main div that has a background image filling the screen. While I've managed to make the image change constantly, the problem arises when the divs on top of the background div also fade out, making the whole page go bla ...

Using an additional router-outlet in an Angular 2 application: a step-by-step guide

I have been facing an issue with my angular2 app where I am attempting to use 2 router-outlets. Despite reading numerous blogs and conducting multiple Google searches, I have not been able to make it work. I would greatly appreciate any suggestions on why ...

Bringing in Data with Angular

For my Angular projects, I attempted to utilize csv files in the following manner: import * as data1 from "./data.csv"; import * as data2 from "./data2.csv"; These files are situated in the same directory as the .ts file that I am trying to access them w ...

Modifications made to Angular 7 templates are not appearing in MVC 5

Currently, I am utilizing Angular 7 with MVC5 in Visual Studio 2019. However, I have encountered an issue while trying to render the Angular template in my index.cshtml file. I access the Angular template in index.cshtml using ``. The template loads perfec ...

Efficiently transferring input to a Typescript file

Is there a better way to capture user input in Angular and pass it to TypeScript? <form > <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" /> </form> The current method involves creating a ...

Keep rolling the dice until you hit the target number

Currently, I am in the process of learning JavaScript and one of my projects involves creating a webpage that features two dice images, an input box, and a button. The objective is for users to input a value, click the button, and then see how many rolls i ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Struggling to Decode Octet-stream Data in Angular 6 HttpClient: Encountering Parsing Failure with Error Prompt: "Failed to parse HTTP response for..."

Is there a way to make a non-JSON request to the server using Angular 6 HttpClient (@angular/common/http) in order to receive an Octet-stream? Below is the code I have tried: getFile(file: any) { let headers = new HttpHeaders({ 'Content-T ...

Is there a way to retrieve the object property within the subscribe function in order to display the HTML content?

Is there a way for me to update the HTML using the properties obtained within .subscribe? I am aware that .subscribe is asynchronous and therefore returns an undefined value initially, but how can I ensure it waits until the value is resolved? Currently, I ...

PHP ajax needs to solely showcase error messages upon form submission

When I submit my form data to a PHP file, it checks for any errors. However, it also returns success before redirecting through AJAX. My goal is to only display an error message if there is one, and if successful, redirect to another page. AJAX: $("#msf ...

Just change "this.array[0]..." in the TypeScript code

There is a problem, this.myList[0], this.myList[1], this.myList[2], this.myList[3], // mylist data is 0 ~ 18... this.myList[18] I attempted to solve it by doing the following: for (let i = 0; i < this.myList.length; i++) { this.myList.push( ...

Tips for utilizing a function to assess ngClass conditional statement in Angular 2

So as I loop through my list using *ngFor, the code snippet is like this: [ngClass]="{'first':isStartDate(event,day)}" The function isStartDate is defined in my component. An error message appeared: "Unexpected token : " ...

Is it acceptable to post variables using AJAX for processing?

Is there a way to send data with AJAX using the code provided? It seems like the information is not being sent to the PHP file as intended. Here is the code snippet: $('#send').click(function(){ var pseudo = $('#psd').val(); }) ...

Transmit information using JSON format in Angular 8 using FormData

i am struggling with sending data to the server in a specific format: { "name":"kianoush", "userName":"kia9372", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd7d5ddd8ce85...@example.com</a>" } H ...