如何从 angular 中的订阅内部访问在函数作用域上声明的变量

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

我的问题很简单。我有一个 Angular 组件,在该组件内部,我有一个这样的函数:


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
    }
}

如您所见,要更新 this.somethingCollection 我需要 something.id,但在订阅中我无法访问它。

有谁知道如何访问订阅内函数范围内的变量?

重叠函数问题可以通过使用范围链存储对父函数 this 的引用来防止 this 的值消失。

因此,当您将 this 的值赋给它时,请使用 selfcontext$this 或任何其他词。它像任何其他常规变量一样被锁定。

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
    }
}

这不是真的

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


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

}

看到一个fool stackblitz