Utilizing Angular, I have a class with several Dependency Injection (DI) variables. During normal execution of a method within the class, everything functions as expected and I can access the injected instances of the DI variables.
Now, my goal is to create a generic modal that will show error text to users if a specific function in the app encounters an error. This modal will also give users the option to retry their last action. To achieve this, I thought about passing a reference to the method the user previously attempted and linking it to the onclick event of a button to create the retry functionality. While this approach works and the intended method is triggered when the retry button is clicked, the method throws an error because the DI variable used within it is undefined.
I'm unsure why this issue is occurring - could it be related to closures? Without passing a reference to the dependency, I'm not sure how to resolve it. However, including a reference goes against the idea of keeping the modal generic.
/*
* This is the method initially triggered by the user, and its reference is passed
* to displayGenericModal if it fails.
* this._classSandbox.loadClasses(); includes an HTTP request, which may fail
*/
syncClasses() {
this.syncingClasses = true;
this._classSandbox.loadClasses(); //this._classSandbox becomes undefined during execution from the generic modal.
}
displayGenericModal(errorKey: string, retryFunction: Function, retryParams: any[]) {
this._genericErrorModal.open(this._dialog, {
errorKey: errorKey,
retryFunction: retryFunction, //This references syncClasses()
retryFunctionParams: retryParams
});
}
/*
* This service is accessed through the this._genericErrorModal variable
*/
export class GenericErrorModalService {
constructor() { }
public open(dialog: MatDialog, params: GenericErrorModalParams) {
dialog.open<GenericErrorModalComponent, GenericErrorModalParams>(GenericErrorModalComponent, {
data: params
})
}
}
To clarify, upon the initial execution of the syncClasses()
method, everything functions correctly. If the HTTP request inside this method fails, a reference to this method is passed to the GenericErrorModalService.open()
method. When the modal is opened and the retry button (containing the reference to the syncClasses()
method) is clicked, the method fails due to this._classSandbox
being undefined.