[英]Cannot access property of an object created inside function of another object in javascript
[英]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
的當前對象。 當處理程序是一個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(this)
this
對象傳遞給外部執行函數,例如回調或promises:
function(){
//code what will be execute out from current object
}.bind(this)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.