The property 'service' is undefined and cannot be read

For some reason, I am unable to access or locate the service even though I have successfully accessed it in other scripts before.

After injecting my service which includes the function to add a customer to the database, I am trying to access it within nested loops and conditional statements. However, I am facing an issue where even the injected firestore cannot be reached. I am completely clueless about why this is happening. Can anyone provide assistance?

 constructor(
    public service: CustomerService,
    public firestore: AngularFirestore,
    ) { }



    scanImage() {
    console.log('>>>> Customer Scanning Image...');
    
    for (let image = 0; image < this.images.length; image++) {
      Tesseract.recognize(this.images[image]).then(
        function(result) {

        
        const newLine = result.text.split('\n');

        
        for (let line = 0; line < newLine.length; line++) {

          
          const word = newLine[line].split(' ');


          
          if (word[word.length - 1] === '>') {
            console.log(`>>>> time: ${word[0]}`);
            console.log(`>>>> code: ${word[1]}`);
            console.log(`>>>> name: ${word[2] + ' ' + word[word.length - 4]}`);
            console.log(`>>>> total: ${word[word.length - 3]}`);
            console.log(`>>>> status: ${word[word.length - 2]}`);
            console.log('______________________\n');

            const data: Customer = {
              time: word[0],
              code: word[1],
              name: word[2] + ' ' + word[word.length - 3],
              total: word[word.length - 2],
              status: word[word.length - 1]
            };

            this.service.add(data);
            
          }
        }
      });
    }
  }

Answer №1

The issue lies within your function(result) {...} function. Once you run your code inside it, a new scope is created, causing this to now refer to the context of the function.

Instead, opt for an arrow function that retains the class's scope.

Here's an example illustrating this concept:

class Test {
    withArrowFunction() {
        (() => console.log(this))();
    }

    withNormalFunction() {
        (function() {
            console.log(this);
        } )();
    }
}

const test = new Test();
test.withArrowFunction();
test.withNormalFunction();

Observing the results, the arrow function correctly accesses the instantiated object while the normal function's this ends up being undefined.

Answer №2

Consider trying Arrow function expressions as a replacement for function(result) {...}.

When you use an arrow function, it doesn't have its own this. Instead, it relies on the this value of the surrounding lexical scope;

Tesseract.recognize (this.images[image]).then(
    (result) => {
        const data = {}
        this.service.add(data); // This references the class scope and remains valid.
    }
)

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

When a file is modified in Angular, it triggers an error prompting the need to restart the 'npm' service

Whenever I make changes to a file in my Angular application, I encounter the following error: ERROR in ./src/app/@theme/components/auth/index.js Module build failed: Error: ENOENT: no such file or directory, open 'C:\Dev\Ng\ngx-a ...

Angular: Handling route segment configuration based on the URL

Consider a situation where you have a URL like /path/path2/path3/123;sdf=df and a predefined routes configuration: { path: 'path', data: { g: 'h' }, children: [ { path: 'path2', data: { c: 'd' }, children: [ { ...

Unable to execute the Vite project

I ran into an issue with my Vite project yesterday. I closed it and now that I have reopened it, the 'npm run dev' command is throwing an error. My project is built using Vite with React and TypeScript. Attached is a screenshot of the error mess ...

Encountering a 400 bad request error while trying to retrieve an authentication token from an API url in Angular

I encountered a problem in my Angular 6 application where I am receiving an Http 400 Bad Request error when attempting to call the API url for login token. The interesting thing is that the API works perfectly fine when accessed through POSTMAN. However, ...

Tips on mocking a function using Jest

I'm currently working on testing a typescript class using Jest. Here is the class I am trying to test: //MyClass.ts import { foo } from './somewhere/FooFactory'; export class MyClass { private _state : number; constructor( arg : string ...

Is it possible to create a destructor specifically for handling RXJS Observables?

I am working on an Angular application where I need to receive SSE events from a server and then process the data. After some research, I came across a solution that involves wrapping the SSE EventSource into an Observable. Here is the code snippet: impor ...

Angular ReactiveForms not receiving real-time updates on dynamic values

I'm using reactive forms in Angular and I have a FormArray that retrieves all the values except for product_total. <tbody formArrayName="products"> <tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i"> ...

What is the best way to verify the [routerLink] values displayed from an Angular component string array?

I want to display the [routerLink] values coming from a string array in my Angular component. This is the TypeScript code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: & ...

Steps for cloning a repository from BitBucket to package.json as a dependency, then building and packaging it

I'm currently working on a main project that has numerous dependencies. Some of these dependencies are installed directly from npm, while others need to be cloned and built from Bitbucket as libraries. Right now, I have to individually clone/pull them ...

trouble with the layout of the table

Could you assist me in improving the design to enhance data clarity? Your help would be greatly appreciated. Thank you for your anticipated response. CSS File: table-layout: fixed; width: 100%; border-collapse: collapse; table-layout: fixed; ove ...

Angular micro front-end powered by module federation

I am interested in developing micro front-end applications using module federation. I have successfully implemented it following the guidelines provided on this informative page. However, I am facing a challenge where I want each project to have its own u ...

Tips for resolving the error of encountering a forbidden and unexpected token in JSON at position 0 while using React hooks

const [forecastData, setForecastData] = useState({ forecast: []}); useEffect(() => { let ignore = false; const FETCHDATA = async () => { await fetch(forecast,{ headers : { ...

Is it possible to transmit an argument to a function without using parentheses?

I am currently working with the following code snippet: this.somePromiseFn<T> // this function is actually a promise .then(res => res as T) .catch(err => this.handleError<T>(err)); handleError<T>(err: HttpErrorResponse) { // pe ...

Having trouble applying [formControl] to a set of radio buttons in Angular2

Currently, I am encountering an issue with a list of groups of radio buttons in Angular2. My objective is to bind the value of each group of radio buttons using [formControl]. However, when implementing this, the radio buttons seem to lose their normal mut ...

What causes arrays to unexpectedly change in Angular?

Currently, I am working on a project that involves Angular and Laravel. One interesting issue has arisen in one of my components where I receive a variable from the database as an object array. Surprisingly, even though I only loop through this variable wi ...

When utilizing useRef and useCallback in React, the output is visible in the console log but does not appear on the page

When working with API data, it's important to remember that the extraction process is asynchronous and the state may not be available at certain times. To handle this situation, we can utilize useCallback. However, even after successfully logging the ...

Tips for simulating an observable value from a service in Angular 7

Struggling to write unit tests for my Angular component, particularly in mocking a single observable value. The service call retrieves data for the component using an observable that is set to true once the call is complete. I have successfully mocked the ...

In Angular, you can achieve two-way binding between a mat tab group and an array in your typescript file. But what's the best way to programmatically switch to a specific mat-tab using types

Check out the code snippet below. I have a mat tab group with a mat tab corresponding to each ValidationStep object in the validationSteps[] array in my TypeScript file through two-way binding. Whenever I add a new element to the array, a new tab is dynam ...

Steps for downloading a file using Selenium in Python while invoking ng-clickWant to learn how to

Attempting to download a file from a website using Selenium Python by clicking a button defined with ng-click. The HTML file contains the following code: <div class="col-lg-6 btn-group"> <br/> <br/> <input type="button" ng-clic ...

Unexpected issue encountered during the Angular 9 compilation process

Since migrating to Angular 9, I've encountered an issue with my feature branch after a rebase. Trying to switch to develop and update it using pull origin develop, everything seemed fine until I came across this error that's leaving me puzzled: h ...