Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Module Separation - Best Practice for shared or common code

I have some Angular services that have identical methods for parsing the json response, handling errors etc (eg. trapping if it's a 422 error for example).

Obviously I don't want these methods copy and pasted into each service, but I cannot seem to find any guidance on where I should put this code.

They are not class methods, just currently identical private methods in each service.

Here's one for example:

   private parseToString(jsonResponse: any){
    return Object.keys(jsonResponse).reduce(
      (prev, next) => prev.concat(jsonResponse[next].map(
        v => next + ' ' + v).join(', ')), []).join(', ');
  }  

Is there some way to create a helper module or something like a Rails Concern that you can include?

Say for example I have this folder:

app/services

which has my various .ts service files.

I could create "app/services/helpers" folder and put a file inside that...but what goes into that .ts file?

eg. parser-helper.ts could be the file name, but what does the code inside that look like? Should it be a module? If so, how can I include it into the service?

For example, is this the recommended way to do it?

app/services/helpers/parser-helper.module.ts

module parserHelperModule {

  export function helperA(){}
  export function helperB(){}

}
like image 442
rmcsharry Avatar asked Apr 24 '26 13:04

rmcsharry


1 Answers

In parser-helper.ts:

export function parseToString(jsonResponse: any): string {
    ...
}

In any other TypeScript file:

import { parseToString } from './relative/path/to/parser-helper';

...
const s = parseToString(response);
like image 75
JB Nizet Avatar answered Apr 27 '26 06:04

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!