问题
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(){}
}
回答1:
You can have the common code as a common service itself as below
export class CommonService {
public parseToString(jsonResponse: any){
return Object.keys(jsonResponse).reduce(
(prev, next) => prev.concat(jsonResponse[next].map(
v => next + ' ' + v).join(', ')), []).join(', ');
}
public someOtherMethod(){
}
}
So you can import the class anywhere accross the application and use them
Note: When you are defining common methods in to a single service, make sure they are public
Update 1 :
Yes it is a good practice to use a separate module that serves all the common codes and making the main AppModule to import the CommonModule which would look like.
@NgModule({
imports: [
HttpModule, Logger, Toaster, ...
],
declarations: [ CommonCmoponents
],
providers:[Service1, Service2 ]
})
export class CommonModule { }
Make sure that your common module just serves as a collection, this CommonModule should not contain
- Browser Module
- Bootstrapping Components
You might be look for a the below image to have separation of concerns
回答2:
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);
来源:https://stackoverflow.com/questions/42328596/angular-module-separation-best-practice-for-shared-or-common-code