Currently, I am in the process of developing a new product and have set up both back-end and front-end projects. For the front-end, I opted to use Angular framework with Typescript. As a newcomer to this language (just a few days old), I have encountered a question regarding callbacks and how to avoid explicit passes with the "this" context. I have come across some resources that I will link for further information.
In the code below, I am creating a wrapper for the HttpClient. The basic idea is that flow control with modals following a plugin architecture (backed by angular routing) works best when complemented with a central delegation using observers and subscribers to broadcast errors like 401 for a graceful re-entry (in my opinion). We won't delve deeper into that topic here, but providing this context may be helpful.
Here is the essence of my code: The Wrapper =>
export class WebService {
constructor(private httpClient: HttpClient,
private exceptionService<Exception>) { }
public post<T>(url: string, dataToPost: any, callBack: (responseData: T) =>
void, callBackInstance: any): void {
this.httpClient.post<T>(url, dataToPost).subscribe(
(data: T) => {
callBack.call(callBackInstance, data);
},
(error: HttpErrorResponse) => {
this.exceptionService.notify(error);
}
);
At this point, I can explicitly manage the "this" context for the callback by using .call(). While I do not mind utilizing this method in your suggestions, it's worth noting that the method requires you to pass in the desired "this" context (callbackInstance). This adds a level of responsibility on the caller of the method that I find unnecessary. To me, a class is somewhat akin to an array with the "this" as an initial displacement. Since I am passing in the callback method, is there a way to inspect that method to derive the appropriate "this"? Perhaps something like: callbackInstance = callback.getRelativeContext(); callBack.call(callBackInstance, data); This would remove the extra parameter, making the method less error-prone for my team to use.
I welcome links to relevant resources, so feel free to share if you can provide a more targeted reference.
Links:
For updating the "this" context
Parameter callbacks
EDIT: Based on the accepted answer, I derived and implemented a test case:
const simpleCallback = (response) => {holder.setValue(response); };
service.post<LoginToken>(Service.LOGIN_URL, '', simpleCallback);