Typescript:将一个方法作为另一个方法的参数传递

时间:2020-03-04 11:11:52

标签: javascript angular typescript ecmascript-6

在我的角形应用程序中,我进行了这种处理:

this.myServiceOne.getDataOne().subscribe((res => {this.variableOne= res}));
this.myServiceTwo.getDataTwo().subscribe((res => {this.variableTwo= res}));
this.myServiceThree.getDataThree().subscribe((res => {this.variableThree= res}));
this.myServiceFour.getDataFour().subscribe((res => {this.variableFour= res}));

我的目的是以这种方式创建通用函数:

  loadData(myVariable, myserviceMethod){
    serviceMethod().subscribe((res => {pefVar = res}));
  }

然后像这样替换我的治疗方法:

this.loadData(this.variableOne, this.myServiceOne.getDataOne);

但这似乎行不通,并且无法理解该注入:(this.myServiceOne.getDataOne)

您的建议?

1 个答案:

答案 0 :(得分:0)

要委派局部变量的设置,您要么传递某种回调(就像您当前在subscribe中所做的那样),要么传递您要更新的属性的名称。

除非有一些重复的代码,而您的示例中没有,否则您真的不会通过使其通用化来节省很多精力。

如果您真的想要编写通用函数,则可以将以下方法作为起点:

回调

从可观察对象返回的对象的类型是通用的。 Tee回调接受相同类型的单个参数。

loadData<T>(serviceMethod: Observable<T>, action: (value: T) => void) {
  serviceMethod.subscribe((res: T) => action(res));
}

您将这样调用:

this.loadData(this.myServiceOne.getDataOne(), res => this.variableOne = res);

属性名称

TKey必须是AppComponent上的命名键。

TValue是该命名键的类型,也是从可观察对象返回的对象的类型。

loadData2<TKey extends keyof AppComponent, TValue extends AppComponent[TKey]>(    
  serviceMethod: Observable<TValue>, 
  key: TKey
): void {
  const component: AppComponent = this;
  serviceMethod.subscribe((res: TValue) => {      
    component[key] = res;
  });
}

您将这样调用:

this.loadData(this.myServiceOne.getDataOne(), 'variableOne');

属性名称(完全通用)

T是组件的类型。

TKey必须是T上的命名键。

TValue是该命名键的类型,也是从可观察对象返回的对象的类型。

loadData2<T, TKey extends keyof T, TValue extends T[TKey]>(    
  component: T,
  serviceMethod: Observable<TValue>, 
  key: TKey
): void {
  serviceMethod.subscribe((res: TValue) => {      
    component[key] = res;
  });
}

您将这样调用:

this.loadData(this, this.myServiceOne.getDataOne(), 'variableOne');

承诺

您也可以将observable转换为promise并使用async / await,但我真的不知道这样做的意义。

演示:https://stackblitz.com/edit/angular-btfqng