【问题标题】:Can you curry functions passed as @Input in Angular你能在 Angular 中对作为 @Input 传递的函数进行 curry
【发布时间】:2021-09-14 02:58:35
【问题描述】:

我有一组样式相似但行为完全不同的模式,我想在我的应用程序的不同场景中使用。因此,我使用它们的最简单方法是在各种场景中将逻辑作为输入传递。使用简单的功能它就可以工作(假设我的custom-button 在点击时需要() => Observable<any>,所以它可以正确锁定直到回调:

export class SimpleComponent {
  @Input() fetchFun: () => Observable<any>;
}

export class ParentComponent {
  funToPass = () => this.httpService.getClients().pipe(...);
}
// in parent component
  <simple-component
    [fetchFun]="funToPass">
  </simple-component>

// in simple component
  <form>
    <custom-button
      type="submit"
      (onClick)="fetchFun"
    ></custom-button>
  </form>

但是,一旦我尝试使用子组件中的参数对这些函数进行 curry,我就会得到 core.js:4610 ERROR TypeError: ctx.curriedFun is not a function,例如:

export class CurryComponent {
  @Input() curriedFun: (dto: Dto) => () => Observable<any>;
}

export class ParentComponent {
  funToPass = (dto:Dto) => () => this.httpService.getClients(dto).pipe(...);
}
// in parent component
  <curry-component
    [curriedFun]="funToPass">
  </curry-component>

// in simple component
  <form>
    <custom-button
      type="submit"
      (onClick)="curriedFun(this.getDto())"
    ></custom-button>
  </form>

我可以将这样的函数传递给 Angular 组件,或者以某种方式解决这个问题吗?

【问题讨论】:

  • 正确的方法是使用@Injectable 服务类。将方法放在那里并在两个组件中注入服务。
  • 不是(onClick)="fetchFun()"? -看括号-顺便说一句,看看uiTeam的回复(对我来说最好使用@Output
  • @Eliseo 不,fetchFun() 计算结果为 Observable&lt;any&gt;,而 custom-button 需要 () =&gt; Observable&lt;any&gt;

标签: javascript angular typescript functional-programming currying


【解决方案1】:

在这种情况下使用@output。单击您的模态component 按钮时触发eventemitter。在您的父组件上捕获该事件并根据您的父组件逻辑执行不同的方法。换个思路,与其把函数传给子代,不如把数据从子代传给父代,把函数逻辑写在父代里。

结构:

<parent-component>
 <modal-component></modal-component> 
</parent-component>

//模态组件

@Output() valueChange = new EventEmitter<string>();

 buttonClick(value: any) {
   this.valueChange.emit(value);
 }

//模态html

<button (click)="buttonClick(value)">Pass to parent</button>

//父级html

<parent-component (valueChange)='buttonClicked($event)'></parent-component>

//父组件

buttonClicked(event){
 //click logic
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2021-04-19
    • 2016-07-17
    • 2023-04-02
    • 2014-08-13
    相关资源
    最近更新 更多