【问题标题】:Typescript : pass a method as a parameter of another method打字稿:将方法作为另一个方法的参数传递
【发布时间】:2020-03-04 11:11:52
【问题描述】:

在我的 angular 应用中,我有这样的处理方式:

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)

您的建议?

【问题讨论】:

  • 通过定义一个泛型函数,您是否试图找到一种干净的方式来处理初始处理?你会接受通常的 rxjs 最佳实践来实现它吗?
  • @YuchaoWu 我试图让它几乎是通用的
  • 什么不起作用,你得到什么错误?

标签: javascript angular typescript ecmascript-6


【解决方案1】:

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

除非有一些重复的代码,而你的示例中没有,否则将其设为通用并不会节省太多精力。

如果您真的想要编写一个泛型函数,您可以将这些方法作为起点:

回调

从 observable 返回的对象的类型是通用的。 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 是该命名键的类型和从 observable 返回的对象的类型。

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 是该命名键的类型和从 observable 返回的对象的类型。

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

【讨论】:

  • 也可以传成员密钥(如res =&gt; this[key] = res),则不需要回调
  • 是的,只要你约束key保证它是组件的成员,否则你就失去了类型安全。
猜你喜欢
  • 1970-01-01
  • 2018-08-08
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多