【发布时间】:2019-10-10 20:03:33
【问题描述】:
假设需要使用条件,它做同样的事情,但调用不同的方法。
const c = true; // for example sake
let b = '';
if (c) {
b = 'method1';
} else {
b = 'method2';
}
function a(){
this.service.b(filter).subscribe((result) =>{
// stuff happens
});
}
是否可以使用变量b作为动态变量来调用服务中的方法?
根据例子更新了sn-p,我可以做如下的:
if (this.title == 'Students') {
this.studentService.getStudents().then(results=> this.lists = results);
} else {
this.studentService.getCandidates().then(results => this.lists = results);
}
但是有没有可能做这样的事情:
this.studentService.get[this.title]().then(results=> this.lists = results);
正如副本所说,它不会那样工作。
【问题讨论】:
-
service.b应该是service[b] -
@Rajesh 似乎不是访问服务的方式。我的意思是,如果我使用像
this.service.method1(filter).....和this.service.method2(filter)....这样的传统方式,过程相同。它可以完成这项工作,但它不是 DRY。 -
根据我的理解,您在服务对象中有
method1/method2,您需要调用它,但方法的名称存储在b中。如果这是正确的,service[b]将返回方法的引用并添加(...)将调用它。所以除非我理解错了,否则它应该可以工作 -
提供一个更完整的示例,其中“method1”和“method2”以您期望的方式存在。实现一个基本示例,其中 'this' 和 'this.service' 有意义,这样我们就可以了解您如何尝试访问 method1 和 method2
-
好的,如果
this.title可以等于'Students'或'Candidates',并且this.studentService有方法getStudents和getCandidates,那么你可以做this.studentService[`get${this.title}`]()
标签: javascript angular typescript