[英]what is the best way to programmatically pass a type to a service?
Using Angular4 I have created services for different databases.使用 Angular4,我为不同的数据库创建了服务。 Each databases' actions are the same (kinda like CRUD) but have a different API endpoint (but exactly the same functions.)
每个数据库的操作都是相同的(有点像 CRUD),但具有不同的 API 端点(但功能完全相同。)
I was creating a service for each database but I am thinking there must be a better way to manage this.我正在为每个数据库创建一个服务,但我认为必须有更好的方法来管理它。
Is there a way to pass a "name" to a service during an import or in a component so that the service will know which endpoint should be hit?有没有办法在导入期间或组件中将“名称”传递给服务,以便服务知道应该命中哪个端点?
Example:例子:
import {ApiService} from '../_services/api.service.ts';
and in the service:并在服务中:
let endpoint = enter code here defined from import of component
private url = '/api/' + endpoint
Something like就像是
@Injectable()
abstract class ApiService {
protected endpoint;
protected get url() {
return '/api/' + this.endpoint;
}
constructor(protected http: Http) {}
getItems() {
return this.http(this.url);
}
}
class SomeService extends ApiService {
protected endpoint = 'some';
}
Notice that endpoint
is defined as a field and url
is read-only accessor, this allows to maintain proper order in child class.请注意,
endpoint
被定义为一个字段,而url
是只读访问器,这允许在子类中保持正确的顺序。
A WETter version (also allows child classes to inject additional dependencies) is: WETter 版本(也允许子类注入额外的依赖项)是:
@Injectable()
abstract class ApiService {
constructor(protected http: Http) {}
...
}
@Injectable()
class SomeService extends ApiService {
constructor(http: Http /*, protected some: Some */) {
super(http);
}
...
}
If same dependency persists in both parent and child class, it should have protected
access modifier in parent class only.如果父类和子类中都存在相同的依赖项,则它应该只在父类中具有
protected
访问修饰符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.