Issue
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?
Solution
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
}
}
Answered By - Hyunjune Kim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.