kisonay kisonay - 3 years ago 120
TypeScript Question

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

Using Angular4 I have created services for different databases. Each databases' actions are the same (kinda like CRUD) but have a different API endpoint (but exactly the same functions.)

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?


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

Answer Source

Something like

abstract class ApiService {
  protected endpoint;
  protected url;

  constructor(...) {
    this.url = '/api/' + this.endpoint;

  getItems() {
     return this.http(this.url);

class SomeService extends ApiService {
  protected endpoint = 'some';

Notice that endpoint is defined as a field and url is assigned explicitly in constructor, this allows to maintain proper order in child class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download