【发布时间】:2016-05-28 00:51:03
【问题描述】:
我正在尝试使用以下方法构建通用存储库:
- 打字稿
- ES6
- Angular 1.x
但我不知道应该如何注入实体然后获取它的模块名称。
我要取名字的原因: 是因为我遵循一个命名约定,其中一个名为 order-count.ts 的文件应该呈现 URL '/order/count'
这可以用 Typescript/Javascript 解决吗?
这是我所拥有的:
order-module.ts
import {App} from '../../App';
import {OrderService} from './order-service';
const module: ng.IModule = App.module('app.order', []);
module.service('orderService', OrderService);
order-service.ts
import {CrudService} from '../../shared/services/crud-service'
import {OrderCount} from '../order/entities/order-count';
export class OrderService {
// @ngInject
constructor(private crudService: CrudService<OrderCount>) {
this.crudService = crudService;
}
getOrders() {
var promise = this.crudService.getAll();
promise.then(response => {
console.log(response, 'success');
}, error => {
console.log(error, 'failed');
});
}
}
order-count.ts
import {Entity} from '../../../shared/models/entity';
export class OrderCount extends Entity {
storeId: string;
storeName: string;
}
entity.ts
export interface IEntity {
id: number;
}
entity.ts
import {IEntity} from '../../module/contracts/entities/entity';
export class Entity implements IEntity {
new() { }
id: number;
}
crud-service.ts
'use strict';
import { Entity } from '../models/entity';
import { EndpointService } from './endpointService';
export class CrudService<TEntity extends Entity> {
private baseCallPath: string;
private entity: { new (): Entity };
// @ngInject
constructor(private endpointService: EndpointService, private $http: ng.IHttpService) {
this.baseCallPath = new this.entity().constructor.name.replace('-', '/');
}
getAll(): ng.IHttpPromise<any> {
return this.handleResponse(
this.$http.get(this.endpointService.getUrl(this.baseCallPath)),
'getAll'
);
}
handleResponse(promise: ng.IHttpPromise<any>, callerMethodName: string): ng.IHttpPromise<any> {
return promise.success((data: any) => {
Array.prototype.push.apply(this.baseCallPath, data);
}).error((reason: any) => {
console.log(this.baseCallPath + callerMethodName, 'ERROR', reason);
});
}
}
endpoint-service.ts
export class EndpointService {
private baseUri: string = 'http://localhost:3000/api/';
getUrl(moduleName: string): string {
return this.baseUri + moduleName;
}
}
【问题讨论】:
-
实体未定义为 Angular 服务,这意味着它不能通过 Angular DI 注入。目前尚不清楚“ES6 模块名称”可能指的是什么,但如果您想在应用程序中找出“../../../shared/models/entity”字符串,那么不,这是不可能的.
-
@estus 我知道我没有将实体定义为 Angular 服务。问题是我将有多个扩展实体类的类。那么这可以在不使用角度注入的情况下解决吗?关于 ES6 模块名称,这就是我的意思,但正如你所说,我认为这可能是不可能的。有没有机会我可以使用类名?将能够将其解析为 URL。
标签: javascript angularjs generics typescript ecmascript-6