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