【发布时间】: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<any>,而custom-button需要() => Observable<any>
标签: javascript angular typescript functional-programming currying