Shaun Luttin Shaun Luttin - 2 months ago 13
TypeScript Question

Access an injected dependency inside a function that we pass to another object

Apologies for not really knowing how to phrase this question. The crux is that on redirect back to the app, the redirect handler needs to have access to the injected

UserManager
.

import { autoinject } from "aurelia-framework";
import { UserManager } from "oidc-client";
import { OpenIdConnectRouting } from "./open-id-connect-routing";

@autoinject
export class OpenIdConnect {

constructor(
private routerConfigurationService: OpenIdConnectRouting,
public UserManager: UserManager) { }

public Configure(routerConfiguration: RouterConfiguration) {

this.routerConfigurationService.ConfigureRouter(
routerConfiguration,
this.PostLogoutRedirectHandler);
}

public PostLogoutRedirectHandler = (): Promise<any> => {
return this.UserManager.signoutRedirectCallback(null);
}
}


The above code passes the
PostLogoutRedirectHandler
to a routing service, so that, when the user returns from the authorization server, the handler will fire.

The above code works, but the handler is lamda only to capture the current object in
this
. When the handler is instead a
function
,
this
is not what we expect it to be and we lack access to the injected
UserManager
object.

Why does the above code work with a lambda but not with a function? Is using a lambda a reasonable approach? If not, is there a way to do this with a function?

Edits:

This is the function/method version of the above handler.

public PostLogoutRedirectHandler(): Promise<any> {
this.logger.Debug("PostLogoutRedirectHandler");
return this.UserManager.signoutRedirectCallback(null);
}


It throws the following error:


Cannot read property 'UserManager' of undefined


Of course, using the lambda
arrow function
works. Is this
arrow function
approach a reasonable pattern or an anti-pattern? What are its costs?

Answer

You need to use .bind(this) to pass this object for outer execution function like callbacks or promises:

function(){
  //code what will be execute out from current object
}.bind(this)
Comments