簡體   English   中英

在傳遞給另一個對象的函數內訪問注入的依賴項

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

很抱歉沒有真正知道如何表達這個問題。 問題是重定向到應用程序時,重定向處理程序需要有權訪問注入的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的當前對象。 當處理程序是一個functionthis不是我們期望的,並且我們無法訪問注入的UserManager對象。

為什么上面的代碼只能用於lambda而不適用於函數? 使用lambda是否合理? 如果沒有,有沒有辦法用函數來做到這一點?

編輯:

這是上述處理程序的功能/方法版本。

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

它引發以下錯誤:

無法讀取未定義的屬性“ UserManager”

當然,使用lambda arrow function可以。 這個arrow function是合理的模式還是反模式? 費用是多少?

您需要使用.bind(this) this對象傳遞給外部執行函數,例如回調或promises:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM