如何改进代码并避免重复?

时间:2020-05-18 19:30:52

标签: angular typescript angular8

我有以下代码描述了模型和发射器:

export class Findbyobjectidlatest {
  onChanged = new EventEmitter<Ifindbyobjectidlatest>();
  model = <Ifindbyobjectidlatest>{ pagesize: 10 };
  emit() {
    this.onChanged.emit(this.model);
  }
}

export class Findbycadnum {
  onChanged = new EventEmitter<Ifindbycadnum>();
  model = <Ifindbycadnum>{ pagesize: 10 };
  emit() {
    this.onChanged.emit(this.model);
  }
}

export class Findbycadastnumber {
  onChanged = new EventEmitter<Ifindbycadastnumber>();
  model = <Ifindbycadastnumber>{ pagesize: 10 };
  emit() {
    this.onChanged.emit(this.model);
  }
}

由于类是相似的,我该如何改善它。

我还有存储库类:

class RepositoryModel {
   findbyobjectidlatest = new Findbyobjectidlatest();
   findbycadnum = new Findbycadnum();
   findbycadastnumber = new Findbycadastnumber();
}

然后我用它:

const repositoryModel = new RepositoryModel();

repositoryModel.findbyobjectidlatest.onChanged().pipe().subscribe();

等等

1 个答案:

答案 0 :(得分:0)

您可以使用具有通用类型的基类:

<table style="width:100%">
  <tr>
    <th>SectionName</th>
    <th>FileName</th> 
  </tr>
  <tr>
    <td>Section1</td>
    <td>xml_number_one</td>
  </tr>
  <tr>
    <td>Section2</td>
    <td>xml_number_one</td>
  </tr>
  <tr>
    <td>differentSectionName</td>
    <td>xml_number_two</td>
  </tr>
</table>

然后扩展您的课程。...

class BaseModelEmitter<T extends {pagesize: number}> {
  onChanged = new EventEmitter<T>();
  model = <T>{ pagesize: 10 };
  emit() {
    this.onChanged.emit(this.model);
  }
}

您用于实现此基础的任何类都必须实现该pagesize接口。

或直接使用它,并根据需要跳过扩展名(但扩展名允许自定义):

export class Findbycadnum extends BaseModelEmitter<Ifindbycadnum> { }