I'm learning angular and have a sample login code. This code has a constructor that clears out the credentials when called. My question is: when is the constructor called? Is it once when the code is initialized or every time a method on the controller is called? I might be confusing this with the way my backend dev framework works with DI which runs the constructor for my controllers only once when initialized.
As a followup question, do I need a logout function or will the constructor be good enough?
This is the code I'm looking at currently:
(function () {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['$rootScope', '$location', 'AuthenticationService', 'FlashService'];
function LoginController($rootScope, $location, AuthenticationService, FlashService) {
var vm = this;
vm.login = login;
(function initController() {
// reset login status
AuthenticationService.ClearCredentials();
})();
function login() {
vm.dataLoading = true;
var promise = AuthenticationService.Login(vm.username, vm.password)
.then(function(userInfo){
AuthenticationService.SetCredentials(userInfo);
$location.path('/');
}, function(failedReason) {
FlashService.Error(failedReason);
vm.dataLoading = false;
});
};
function logout() {
AuthenticationService.ClearCredentials();
$location.path('/login');
};
}
})();
- This code is based off of Jason Watmore's blog - http://jasonwatmore.com/post/2015/03/10/AngularJS-User-Registration-and-Login-Example.aspx.
- I have read through the docs here once: https://docs.angularjs.org/guide/controller