简体   繁体   English

以编程方式将类型传递给服务的最佳方法是什么?

[英]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.

相关问题 什么是将数据传递到其他组件的最佳方法 - What is the best way pass data to other components 在Angular 2中调用服务的最佳方法是什么 - What is the best way to call a service in Angular 2 使用 angular 和 Typescript 从 UI 传递标头的最佳方法是什么? - What is the best way to pass Headers from UI using angular and Typescript? 在角度服务中处理来自后端api的数据的最佳方法是什么? - What is the best way to work with data from a backend api in an angular service? 在角度2(Beta)中将一项服务注入另一项服务的最佳方法是什么? - What's the best way to inject one service into another in angular 2 (Beta)? 对我来说,从服务将数据推送到组件的最佳方法是什么? - What is the best way for me to push data to a component from a service? 处理 SPA 的外部无法访问服务的最佳方法是什么? - What's the best way to handle external unreachable service for SPA? 在Angular服务中取消订阅无限可观察量的最佳方法是什么? - What is the best way to unsubscribe infinite observables in an Angular service 在 angular 或 type 脚本中迭代数百万条记录的最佳方法是什么 - What is best way to iterate millions of records in angular or type script 将样式传递给组件的最佳方式 - Best way to pass styling to a component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM