Typescript:注入泛型并获取 ES6 模块名称

2024-02-15

我正在尝试使用以下方法构建通用存储库:

  • 打字稿
  • ES6
  • 角 1.x

但我不知道应该如何注入实体然后获取其模块名称。

我想得到这个名字的原因:是因为我遵循命名约定,其中名为 order-count.ts 的文件应呈现 URL '/order/count'

这可以用 Typescript/Javascript 解决吗?

这是我所拥有的:

订单模块.ts

import {App} from '../../App';
import {OrderService} from './order-service';

const module: ng.IModule = App.module('app.order', []);

module.service('orderService', OrderService);

订单服务.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');
        });
    }
}

订单计数.ts

import {Entity} from '../../../shared/models/entity';

export class OrderCount extends Entity {
    storeId: string;
    storeName: string;
}

实体.ts

export interface IEntity {
    id: number;
}

实体.ts

import {IEntity} from '../../module/contracts/entities/entity';

export class Entity implements IEntity {
    new() { }
    id: number;
}

增删改查服务.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);
        });
    }
}

端点服务.ts

export class EndpointService {
    private baseUri: string = 'http://localhost:3000/api/';

    getUrl(moduleName: string): string {
        return this.baseUri + moduleName;
    }
}

这个链接 https://codereview.stackexchange.com/questions/83107/automating-crud-using-repository-pattern-web-api-and-typescript可能有助于使用 Typescript 实现通用存储库

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Typescript:注入泛型并获取 ES6 模块名称 的相关文章

随机推荐