承诺在 Angular 中设置了 class 的参数后执行函数 4

Promise to execute a function after a parameter of a class was set in Angular 4

我有一个class,而这个class有一个参数"filter"。这个 class 也接受输入 filterChange。在 filterChange 发生变化时,我想将过滤器设置为一个新值,然后执行一个将使用 this.filter 的函数。因为 Angular 2 是异步的,所以我想知道如何保证 filter 在 sampleFunction 运行之前有一个新值。这样做的正确方法是什么?我正在考虑编写一个将 this.filter 设置为 filterChange 然后使用 .then 调用 sampleFunction 的承诺,但似乎我无法在 Promise 范围内使用 "this"。

export class WhosebugExample implements OnChanges{
   filter = 'default';
   constructor(){}
   @Input filterChange;

   ngOnChanges(){
      this.filter = this.filterChange;
      this.sampleFunction(); //how to make sure this gets the updated this.filter value?
   }

   sampleFunction(){
      //uses this.filter;
   }
}

此外,我知道我可以让 sampleFunction 接受过滤器值,并执行类似以下操作:sampleFunction(this.filterChange),但这不是我要寻找的行为。

或者,Angular 是不是像我想象的那样异步,因此这段代码是可以的?

您可以使用set/get ES6 方法实现。

export class WhosebugExample implements OnChanges{
   filter = 'default';
   constructor(){}
   @Input filterChange;
   private previousValue;

   ngOnChanges(){}

   set filterChange(value){
     if(this.previousValue != value){
        this.filter = value;
        this.previousValue = this.filter;
      this.sampleFunction(); //how to make sure this gets the updated this.filter value?
     }
   }

   sampleFunction(){
      //uses this.filter;
   }
}

如果条件可行,则很简单。比较 ngOnChanges 方法

中的 previouscurrent
ngOnChanges(changes : SimpleChanges){
     if(changes['filterChange'] != undefined && 
         changes['filterChange'].previousValue != changes['filterChange'].currentValue) {
         this.filter = this.filterChange;
         this.sampleFunction();
     }
}