Home > database >  How to access a variable declared on function scope from inside subscribe in angular
How to access a variable declared on function scope from inside subscribe in angular

Time:02-22

My question is very simple. I have an Angular component, and inside that component, I have a function like this:


somethingCollection: TypeSomething[]
...
public deleteSomething(something: TypeSomething): void {
    // something is in this scope
    this.someAPI.deleteSomething(something.id).subscribe( (res) => {
       // update this.somethingCollection
       // but cannot access something in outer scope
    }
}

As you may have observed, to update this.somethingCollection I need something.id, but inside the subscribe I lost access to it.

Does anyone knows how to access the variables at function scope inside the subscribe?

CodePudding user response:

Overlapping function problems can prevent the value of this from disappearing by storing references to this of the parent function using the scope chain.

so using the word self, context, $this or anything else when you assign the value of this to it. it is locked in place like any other 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
    }
}
  • Related