简体   繁体   English

如何从 angular 中的订阅访问在 function scope 上声明的变量

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

My question is very simple.我的问题很简单。 I have an Angular component, and inside that component, I have a function like this:我有一个 Angular 组件,在该组件内部,我有一个 function,如下所示:


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.您可能已经观察到,要更新 this.somethingCollection,我需要 something.id,但在订阅中我无法访问它。

Does anyone knows how to access the variables at function scope inside the subscribe?有谁知道如何访问订阅内 function scope 处的变量?

Overlapping function problems can prevent the value of this from disappearing by storing references to this of the parent function using the scope chain.重叠 function 问题可以通过使用 scope 链存储对父 function 的this的引用来防止this的值消失。

so using the word self , context , $this or anything else when you assign the value of this to it.因此,当您将 this 的值分配给它时,请使用selfcontext$this或其他任何词。 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
    }
}

It's not true这不是真的

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

}

see a fool stackblitz看到一个傻瓜 stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM