Home > OS >  Angular - how to extract typescript methods to new files
Angular - how to extract typescript methods to new files

Time:08-13

I've inherited some typescript components in an Angular project, some of which are thousands of lines long. How can I go about a refactor that allows me to move methods into other files and call them from the component? For example, something like

  InitialiseSearchFilter() {
    this.searchListFilter.PageNumber = 1;
    this.searchListFilter.PageSize = 20;
    this.searchListFilter.SortOrder = "asc";
  }

I would like to move out of the component and into a different file, which I can reference from the component, for file size and readability purposes.

CodePudding user response:

I would do something like this:

InitialiseSearchFilter(): { pageNumber: number, pageSize: number, sortOrder: 'asc' || 'desc'} {
    return {PageNumber: 1,PageSize: 20,SortOrder: "asc"}
  }

CodePudding user response:

You can try to make the definition in your component as:

import { CustomComponentB } from 'CustomComponentB';
....
....
....
export class CustomComponent extends CustomComponentB {

And then in the CustomComponentB.ts file you can add some of the properties and methods that were originally on the CustomComponent.

You need naturally to make CustomComponentB a valid class and define everything that gets referenced by the mehtods in CustomComponentB.

Let me know if you try this and it works for you.

  • Related