Exploring ways to retrieve a function-scoped variable from within an Angular subscribe function

Here's the scenario: I have a simple question regarding an Angular component. Inside this component, there is a function structured like this:


somethingCollection: TypeSomething[]
...
public deleteSomething(something: TypeSomething): void {
    // something variable is within this scope
    this.someAPI.deleteSomething(something.id).subscribe( (res) => {
       // need to update this.somethingCollection here
       // but unable to access 'something' in outer scope
    }
}

It's clear that for updating this.somethingCollection, we require 'something.id'. However, once inside the subscribe method, I lose access to it.

Is there anyone who can guide me on how to retain access to function scoped variables within the subscribe method?

Answer №1

When dealing with overlapping function problems, it is crucial to prevent the loss of the value of this by storing references to the parent function's this using the scope chain.

By using aliases such as self, context, $this, or any other variable name when assigning the value of this to it, the reference remains fixed similar to a regular variable.

somethingCollection: TypeSomething[]
...
public deleteSomething(something: TypeSomething): void {
    let self = this;
    this.someAPI.deleteSomething(something.id).subscribe( (res) => {
       self.somethingCollection // access somethingCollection....
       // this.somethingCollection is undefined
    }
}

Answer №2

That statement is not accurate

export class AppComponent implements OnInit  {
  name = 'Angular ' + VERSION.major;
  constructor(private dataService:DataService){}


  public removeItem(item: any): void {
    console.log(item)
    this.dataService.getData(item.id).subscribe( (res) => {
      console.log(item,this.name,res)
    })
  }
  ngOnInit()
  {
    this.removeItem({id:3})
  }

}

view a demo on stackblitz

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

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...

Exploring the dynamic duo of SystemJS and AngularJS 2

I am currently working on integrating the Core Angular2 module into my application, which is written in Typescript. It's essentially following the same structure as the quick start tutorial on the Angular.IO website. However, I am facing a challenge ...

The test failed to execute due to disconnection (0 occurrences) as no message was received within the 30000 ms timeframe

Currently, I am facing an issue with my Angular application. When I execute the "ng test" command, it displays an error message stating 'Disconnected (0 times), because no message in 30000 ms.' I have tried updating both karma and jasmine package ...

Are Handlebars and Angular 2 compatible?

Since the syntax for Angular expressions and Handlebars expressions is the same ({{ }}), I'm curious if we can utilize both at the same time. ...

Instructions for inserting a hyperlink into a column of a table with the *ngFor directive in Angular2

I currently have a table with 4 columns: Name, ID, Department, and City. I am fetching both the row data and column data as an array from a TypeScript file and iterating through them using *ngFor. Below is a snippet of my code: <tbody> <tr *ng ...

Jest encounters an issue while attempting to import Primeng CSS files

I am currently utilizing Jest version 26.6.3 for testing Angular components. Unfortunately, the unit tests for components that utilize Primeng's checkbox component are failing during the compileComponents step with the error message "Failed to load ch ...

What is the process for implementing a new control value accessor?

I have a directive that already implements the ControlValueAccessor interface (directive's selector is input[type=date]) and now I need another directive that also implements ControlValueAccessor with the selector input[type=date][datepicker] - let&ap ...

Angular 5 update causing 'NgModule not found' error

After attempting to upgrade my app to Angular 5, I encountered a series of bugs. Among them, there is one persistent issue that has me stumped. An uncaught error has surfaced: 'Unexpected value HttpClient imported by the module AppModuleShared. Ple ...

I am encountering difficulty accessing my index.html file located in the views directory. Whenever I try to access it through localhost 3000, I receive an error message saying "cannot get"

My files are available for viewing on github at https://github.com/elmoreka/myTaskLIst.git. I'm experiencing issues with my index.html file located in the views directory. When trying to access localhost 3000, I receive an error stating "cannot get". ...

Error: The variable _ is undefined when trying to use the .map() function on an array

While working on my project, I encountered a "ReferenceError: _ is not defined" when using the .map function in this code snippet: arr.map(async (elem) => { ... }); I couldn't find any explicit mention of "_" in my code. The error trace pointed me ...

Handling linting errors for getInitialProps return type in NextJS with Typescript

I've been grappling with this problem for an extended period, and despite numerous attempts, I haven't been able to resolve it. My issue revolves around a basic page named one.tsx. Its structure is as follows: The linting error that's plag ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

What is the best way to execute multiple functions simultaneously in Angular?

Within a form creation component, I have multiple functions that need to be executed simultaneously. Each function corresponds to a dropdown field option such as gender, countries, and interests which are all fetched from the server. Currently, I call th ...

The compatibility issue between the text-mask library and the Angular material datepicker is causing functionality problems

I am currently utilizing the text-mask library (https://www.npmjs.com/package/angular2-text-mask) in an attempt to integrate it with two Angular datepicker components. The functionality works as expected when manually entering the date into the input field ...

Error encountered in Storybook: The value is not iterable (property Symbol(Symbol.iterator) cannot be read)

I recently created a React library using and opted for the React + TypeScript + Storybook template. You can find the entire codebase here → https://github.com/deadcoder0904/react-typical I encountered the following error: undefined is not iterable ( ...

Having trouble manipulating text or values of angular elements with Selenium and Python

https://i.stack.imgur.com/vZdo0.png I am facing an issue with a date input field that does not have a calendar or dropdown for selection. I tried using driver.find_element_by_id('dataInicio').send_keys(date_value) but it doesn't seem to work ...

Angular - Loading images on the fly

After scouring numerous resources, I couldn't find a resolution to my issue. For your information, I am utilizing ASP.net Core 2.0's default angular project In the process of developing an Angular application, I am faced with the challenge of ...

Using Angular with Web API to transmit FormFile data from client to API

I am facing a challenge with creating an object (referred to as a "Ticket") along with 0-n children (known as "Attachments") in my Angular application and sending this information to my dotnet core Web API. However, this is more of a logical inquiry that I ...

How can I structure the response from HttpClient to make it compatible with *ngFor

I need assistance in solving a minor issue. I am working with data from a REST API, which is returned as an array of objects. After receiving this data in my service, I attempt to transform it and push it to a subject to notify my component about the arriv ...

Combine two streams under certain conditions using RxJs

When working with streams, I am facing a scenario where I have two server calls to make in order to get the required response. However, if the first call returns data, I do not want to execute the second call. I have been struggling to find the proper comb ...