Created
August 31, 2021 09:13
-
-
Save eneajaho/28c4ef1d75bf1d8733cec23e54068c0a to your computer and use it in GitHub Desktop.
Provide function with InjectionToken in Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
Component, | |
Inject, | |
inject, | |
Injectable, | |
InjectionToken, | |
NgModule | |
} from '@angular/core'; | |
import { BrowserModule } from '@angular/platform-browser'; | |
@Injectable({ providedIn: 'root' }) | |
export class LoggerService { | |
success(message: string): void { | |
console.log('Success >>>> ', message); | |
} | |
} | |
// export const loggerFn = (message: string): void => console.log(message); | |
export type SuccessLogger = (message: string) => void; | |
export const Logger = new InjectionToken<SuccessLogger>( | |
'Logger Success function', | |
{ | |
factory: () => inject(LoggerService).success | |
// factory: () => loggerFn | |
} | |
); | |
@Component({ | |
selector: 'my-app', | |
template: ` | |
<button (click)="log('hahahaha')"> | |
Log to console | |
</button> | |
` | |
}) | |
export class AppComponent { | |
constructor(@Inject(Logger) public log: SuccessLogger) {} | |
} | |
@NgModule({ | |
imports: [BrowserModule], | |
declarations: [AppComponent], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule {} |
import { inject, Injectable, InjectionToken } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { HttpErrorResponse } from '@angular/common/http';
export function handleServerSideValidation(error: HttpErrorResponse, form: FormGroup): undefined | string {
// if the error isn't with status 422 (Unprocessable Entity) don't do anything
if (error.status !== 422) {
return undefined;
}
const unhandledErrors: any[] = [];
const validationError = error.error?.errors;
Object.keys(validationError || {}).forEach(element => {
const formControl = form.get(element);
if (formControl) {
formControl.setErrors({ serverSideError: validationError[element].join('') });
} else {
// Field is not defined in form but there is a validation error for it, set it globally
unhandledErrors.push(validationError[element].join(''));
}
});
if (unhandledErrors.length) {
return unhandledErrors.join();
}
return undefined;
}
export type HandleHttpErrorFn = (error: Error, form: FormGroup) => void;
export const HandleHttpError = new InjectionToken<HandleHttpErrorFn>(
'Handle Http Error token', {
factory: () => {
const handleErrorService = inject(HandleServerSideValidationService);
return handleErrorService.handleServerSideValidationError;
}
}
);
@Injectable({ providedIn: 'root' })
export class HandleServerSideValidationService {
constructor(private toast: ToastrService) {}
handleServerSideValidationError(error: Error, form: FormGroup): void {
if (error instanceof HttpErrorResponse) {
const unhandledErrors = handleServerSideValidation(error, form);
if (unhandledErrors) {
this.toast.error(error.statusText, unhandledErrors);
}
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Scroll top injection token
Usage
Stackblitz link