2016-09-10 27 views
-1

我在使用Auth0驗證時遇到了問題。我得到的authManager是undefined

我在authManager上未定義身份驗證。

authManager注入到authService,它被添加到應用程序「auth0.lock」,「angular-jwt」被添加到模塊中。

App.ts(run方法):

app.run(["$rootScope", "authManager", "AuthService", 
    function($rootScope, authManager, authService) { 

    // Put the authService on $rootScope so its methods 
    // can be accessed from the nav bar 
    $rootScope.authService = authService; 

    // Register the authentication listener that is 
    // set up in auth.service.js 
    authService.registerAuthenticationListener(); 

    // Use the authManager from angular-jwt to check for 
    // the user's authentication state when the page is 
    // refreshed and maintain authentication 
    authManager.checkAuthOnRefresh(); 

    // Listen for 401 unauthorized requests and redirect 
    // the user to the login page 
    authManager.redirectWhenUnauthenticated(); 

}]); 

AuthService.ts:

class AuthService { 

public userProfile: any; 

constructor(private $rootScope, private lock, private authManager) { 
    this.userProfile = JSON.parse(localStorage.getItem("profile")) || {}; 
} 

public login() { 
    this.lock.show(); 
} 

// Logging out just requires removing the user's 
// id_token and profile 
public logout() { 
    localStorage.removeItem("id_token"); 
    localStorage.removeItem("profile"); 
    this.authManager.unauthenticate(); 
    this.userProfile = {}; 
} 

// Set up the logic for when a user authenticates 
// This method is called from app.run.js 
public registerAuthenticationListener(authManager) { 
    //const self = AuthService._instance; 

    this.lock.on("authenticated", function(authResult) { 
    localStorage.setItem("id_token", authResult.idToken); 
    authManager.authenticate(); // <-- here is the error 

    this.lock.getProfile(authResult.idToken, function(error, profile) { 
     if (error) { 
     console.log(error); 
     } 

     localStorage.setItem("profile", JSON.stringify(profile)); 
     this.$rootScope.$broadcast("userProfileSet", profile); 
    }); 
    }); 
} 
} 


AuthService.$inject = ["$rootScope", "lock", "authManager"]; 
export default AuthService; 

我在服務中添加靜態工廠方法,以及authManager不是不確定的,但它沒有得到在authService構造函數中設置。

下面的代碼:

public static Factory($rootScope, lock, authManager) { 
AuthService._instance = new AuthService($rootScope, lock, authManager); 
console.log("authManager: " + authManager.authenticate); 
return AuthService._instance; 

}

+0

爲什麼要投票而不是幫助? – n3tx

回答

1

將溶液使用打字稿和ES6時:

第一步: app.ts

.service("AuthService", AuthService.Factory) 

第二步: authService

我在工廠中創建了一個新實例,然後通過獲取實例在方法中使用它。 const self = AuthService._instance

相關問題