【问题标题】:Access an injected dependency inside a function that we pass to another object在我们传递给另一个对象的函数中访问注入的依赖项
【发布时间】:2017-02-02 08:59:47
【问题描述】:

很抱歉不知道如何表达这个问题。关键是在重定向回应用程序时,重定向处理程序需要访问注入的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);
    }
}

上面的代码将PostLogoutRedirectHandler传递给路由服务,这样当用户从授权服务器返回时,处理程序就会触发。

上述代码有效,但处理程序是 lamda 仅用于捕获this 中的当前对象。当处理程序改为function 时,this 不是我们所期望的,我们无法访问注入的UserManager 对象。

为什么上面的代码可以使用 lambda 而不是函数?使用 lambda 是一种合理的方法吗?如果没有,有没有办法用函数来做到这一点?

编辑:

这是上述处理程序的函数/方法版本。

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

它会抛出以下错误:

无法读取未定义的属性“UserManager”

当然,使用 lambda arrow function 可以。这是arrow function 方法是合理的模式还是反模式?它的成本是多少?

【问题讨论】:

  • 我不确定我是否得到了问题,但你能不能只 bind 函数?
  • 函数bind是什么意思?
  • 它将this 上下文绑定到您的OpenIdConnect 实例:developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
  • 我认为这篇文章会为你解决问题:stackoverflow.com/questions/28371982/…
  • 我不确定它是否正确,但我怀疑他的意思是像这样绑定函数:this.routerConfigurationService.ConfigureRouter( routerConfiguration, this.PostLogoutRedirectHandler.bind(this));

标签: javascript typescript lambda dependency-injection aurelia


【解决方案1】:

您需要使用.bind(this) 来传递this 对象以用于回调或承诺等外部执行功能:

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

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    相关资源
    最近更新 更多