Angular7 instances encounter the issue of undefined when referencing "this"

After incorporating a custom confirm dialog into a function, I noticed that the reference to "this" became undefined in all parts of the code except for within the dialog function.

The function looks like this:

onDelete(CTId) {
    this.confirmDialogService.confirmThis( 
      "Confirm Delete",
      () => {
          this.service.deleteContactDetail(CTId).subscribe(
          res => {
            this.service.refreshList();
            this.toastr.warning("Deleted Successfully", "Contact Details");
          },
          err => {
            console.log(err);
            this.toastr.error("Failed to Delete");
          }
        );
      },
      () => {
        console.log("closed dialog");
      }
    );
  }

In the definition for the confirmDialogService, "this" is set as this: this, while elsewhere it's defined as any.

Answer №1

It is recommended to utilize arrow functions.

For instance:

function(arg) {
   ...
}

can be written as:

(arg) => {
   ...
}

An advantage of using an arrow function is that it will inherit the scope from the calling method. Thus, this will remain unchanged.

Your code should resemble this example:

onDelete(CTId) {
  this.confirmDialogService.confirmThis( 
    "Confirm Delete",
    () => {
      this.service.deleteContactDetail(CTId).subscribe(
        res => {
          this.service.refreshList();
          this.toastr.warning("Deleted Successfully", "Contact Details");
        },
        err => {
          console.log(err);
          this.toastr.error("Failed to Delete");
        }
      );
    },
    () => console.log("closed dialog")
  );
}

To learn more about arrow functions, check out these resources:

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

Is there a way to resolve the issue of the argument being of type Boolean or undefined in React and TypeScript?

Encountering an issue, Received an error message stating: 'Argument of type 'boolean | undefined' is not assignable to parameter of 'type boolean'. Type 'undefined' is not assignable to type 'boolean'.' ...

Issue with displaying Ng-x spinner in Angular 5 function

Have you ever encountered this issue before? I've noticed that ngx-spinner doesn't work when used within a function, but it works fine when placed inside the subscribed callback. When placed outside of the authservice, the spinner isn't dis ...

Ensuring TypeScript recognizes a class property as definitively initialized when set using a Promise constructor

I have a simple class definition that is giving me an error in TypeScript. class Container { resolveData: (s: string) => void // not definitely initialized error! data: Promise<string> constructor() { this.data = new Promise&l ...

I am looking to store a collection of objects in Firebase using a single request, and I want Firebase to generate a unique key for each object without using array

I am looking to store a set of objects in Firebase using a single request with a unique key generated by Firebase (without using array indexes as keys). let object_list = { '0': { 'title':'title 1', 'time&apos ...

Detecting changes in an object property that is bound to another object property - a comprehensive guide

In my application, I am facing a challenge with displaying navigation items based on user rules. This is how I have tried to implement it: I define an object with the necessary rules: rules: { canSeeProfile: true, canSeeAdminZone: false, ... ...

Issue with Nodemon and Typescript causing errors with Worker Threads

Currently, I am in the process of integrating a worker thread into my Typescript and node.js application. Let's take a look at my thread.ts file: import { Worker, isMainThread, parentPort, workerData } from "worker_threads"; let thread ...

Utilizing Sequelize's Where clause with the flexibility of optional parameters

Can you guide me on writing Sequelize queries with optional parameters? Consider the below query example: const result : SomeModel[] = await SomeModel.findAll( {where: { id: givenId, ...

Navigating with the InAppBrowser in Ionic Angular after a POST request

Currently, I am in the process of redirecting my app to 3DS for a payment method. According to the documentation, the steps involved are: Obtain the action.url and the action.method from the /payments response. Redirect the shopper to the specified URL us ...

The date selected in the date picker does not display in the view until the calendar is opened

I am currently working with two date pickers named startDate and endDate. My goal is to set up a basic date validation system where the start date cannot come after the end date. The main requirement is that if the user selects an end date that is earlier ...

Is it possible to access a class with protected/private fields written in TypeScript from outside the class in JavaScript?

Currently, I am delving into TypeScript classes (though my experience with OOP is limited). The following code snippet is extracted from the chapter on classes in https://www.typescriptlang.org/docs/handbook/classes.html Here's the issue at hand: I ...

Error: Issue with accessing the 'get' property of an undefined value (Resolved issue with incompatible imports not functioning)

Encountering an issue while attempting to execute the karma TS spec file. Despite all modules and imports functioning properly without conflicts, the error persists. I've tried incorporating component.ngOninit() into beforeEach() and it(), but to no a ...

Update the data by appending a textstringValue

Is there a way to update a field value using a string in TypeScript? The following code isn't functioning as expected: fieldName = "myForm.controls.graphicUrl"; this[fieldName].patchValue("hello"); ...

Unveiling the types of an object's keys in Typescript

I am currently utilizing an object to store a variety of potential colors, as seen below. const cardColors = { primaryGradientColor: "", secondaryGradientColor: "", titleTextColor: "", borderColor: "&quo ...

I encountered an issue while trying to install the latest version of AngularFire, receiving an error

Recently, I initiated a new Angular Material project and encountered the following errors: moblizeit@Vikrams-MBP scanbuddyadmin % ng add @angular/fire@latest ℹ Using npm as the package manager ⚠ There are unmet peer dependencies within the package. Add ...

Utilize TypeScript enum keys to generate a new enum efficiently

I am in need of two Typescript enums as shown below: export enum OrientationAsNumber { PORTRAIT, SQUARE, LANDSCAPE } export enum OrientationAsString { PORTRAIT = 'portrait', SQUARE = 'square', LANDSCAPE = 'landscape&ap ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

Double-tap bug with Image Picker in Typescript React Native (non-expo)

Well, here’s the situation - some good news and some bad news. First, the good news is that the code below is functioning smoothly. Now, the not-so-good news is that I find myself having to select the image twice before it actually shows up on the clie ...

Obtaining the count of a specific column in Angular 6 by grouping objects based on the same value in an array

In TypeScript, I have an array of objects and I am using a foreach loop. The array contains 2 columns with a progress value of 100, while the rest have values less than 100. My goal is to calculate the count of columns with a progress value of 100, which ...

The combination of [(ngModel)] and name is not compatible with angular's ng-autocomplete feature, causing it to malfunction

I'm currently integrating ng-autocomplete with Angular 8, and encountering an issue. Here is the code snippet: HTML: <div class="field"> <label class="label">Nombre del condominio:</label> <div class="control"> ...

LeafletJS tiles are only loaded once the map is being actively moved

Currently, I am facing an issue while trying to load a simple leaflet map in my Ionic 2 application. The problem is that not all tiles are loading correctly until the map is moved. this.map = new L.Map('mainmap', { zoomControl: false, ...