Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

typescript - 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(){}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...