繁体   English   中英

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

[英]what is the best way to programmatically pass a type to a service?

使用 Angular4,我为不同的数据库创建了服务。 每个数据库的操作都是相同的(有点像 CRUD),但具有不同的 API 端点(但功能完全相同。)

我正在为每个数据库创建一个服务,但我认为必须有更好的方法来管理它。

有没有办法在导入期间或组件中将“名称”传递给服务,以便服务知道应该命中哪个端点?

例子:

import {ApiService} from '../_services/api.service.ts';

并在服务中:

let endpoint = enter code here defined from import of component  
private url = '/api/' + endpoint

就像是

@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';
}

请注意, endpoint被定义为一个字段,而url是只读访问器,这允许在子类中保持正确的顺序。

WETter 版本(也允许子类注入额外的依赖项)是:

@Injectable()
abstract class ApiService {
  constructor(protected http: Http) {}
  ...      
}

@Injectable()
class SomeService extends ApiService {
  constructor(http: Http /*,  protected some: Some */) {
    super(http);
  }
  ...
}

如果父类和子类中都存在相同的依赖项,则它应该只在父类中具有protected访问修饰符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM