Javascript 角度:将方法作为参数传递
我有两种几乎相似的方法:Javascript 角度:将方法作为参数传递,javascript,angular,typescript,Javascript,Angular,Typescript,我有两种几乎相似的方法: private firstFunction () { this.serviceOne.methodOne().subscribe( res => { return resultOne = res; }, err => {} ); } private secondFunction () { this.serviceTwo.methodTwo().subscribe(
private firstFunction () {
this.serviceOne.methodOne().subscribe(
res => {
return resultOne = res;
},
err => {}
);
}
private secondFunction () {
this.serviceTwo.methodTwo().subscribe(
res => {
return resultTwo = res;
},
err => {}
);
}
我想写一个通用函数,如下所示:
genericFunction (service ,method , result ) {
service.method().subscribe(
res => {
return result = res;
},
err => {}
);
}
因此,我想让这样的东西发挥作用:
genericFunction (serviceOne , methodOne , resultOne );
genericFunction (serviceTwo , methodTwo , resultTwo );
实际上,我找不到如何将
methodOne
和methodTwo
作为参数传递。有什么建议吗?代码中有几个问题
首先,您希望修改作为参数传入的字段(如result=res
所建议)。您不能传入对字段的引用,但可以传入字段名称,并使用索引来更改字段。keyof t
将允许您以类型安全的方式传入字段
其次,如果您想访问服务上的方法。同样,我们可以通过传入方法名称来执行此操作,并且我们可以将服务约束为具有传入方法名称的方法,该方法返回一个可观察的
。可观察的
的结果也可以约束为与我们要访问的字段类型相同的字段将其签名为,以使该方法完全类型安全
declare class Service1 {
method1() : Observable<number>
}
declare class Service2 {
method2() : Observable<string>
}
class MyClass {
resultOne!: number;
resultTwo!: string;
constructor() {
this.genericFunction(new Service1(), "method1", "resultOne");
this.genericFunction(new Service2(), "method2", "resultTwo");
this.genericFunction(new Service1(), "method1", "resultTwo"); // error resultTwo is a string, the method return Observable<number>
this.genericFunction(new Service2(), "method", "resultTwo"); // error method does not exit on Service2
this.genericFunction(new Service2(), "method2", "resultTwo2"); // error field does not exist on type
}
genericFunction<MethodKey extends string, ResultKey extends keyof MyClass>(service:Record<MethodKey, ()=> Observable<MyClass[ResultKey]>>, method:MethodKey, result: ResultKey){
service[method]().subscribe(
res => this[result] = res,
err => {}
);
}
}
请尝试使用以下代码:
private firstFunction () {
let response= genericFunction(this.serviceOne.methodOne())
}
private secondFunction () {
let response = genericFunction(this.serviceTwo.methodTwo())
}
通过只接收一个变量来修改泛型函数
//if it is angular 4 or less
genericFunction (method: Observable) {
return method.map(res => {
return res.json();
});
}
//if it is angular 5 or 6
genericFunction (method: Observable) {
return method.pipe(
map(res => {
return res;
}));
}
这就是你要找的吗?你确定你没有陷入尝试的陷阱吗?我不认为这与角度版本有任何关系。而是取决于他是在使用
Http
还是HttpClient
。同样在上面的示例中,他最终必须订阅response
,才能真正访问响应数据超出了使函数成为泛型函数的全部目的。@SiddAjmera请看这篇文章,对此表示抱歉。仍然无法理解您试图在这里提出的要点。为什么不?作为响应,您将得到由泛型函数提供的泛型响应
//if it is angular 4 or less
genericFunction (method: Observable) {
return method.map(res => {
return res.json();
});
}
//if it is angular 5 or 6
genericFunction (method: Observable) {
return method.pipe(
map(res => {
return res;
}));
}