broadcast listener called twice in angular - javascript

I have a login controller where I am trying to signup/login:
app.controller('signupController', function($scope, $sessionStorage, $state, authService){
$scope.$storage = $sessionStorage;
$scope.socialAuthentication = function(e){
authService.login(e);
};
$scope.logout = function(e){
authService.logout();
};
$scope.$on('authenticate', function(event, data){
console.log('user ', data); // prints twice here
if(data != null && data.access_token != ""){
$scope.$storage.isLoggedIn = true;
} else {
$scope.$storage.isLoggedIn = false;
}
$state.go('home');
});
});
Auth Service:
app.service('authService', function($rootScope, $http){
this.login = function(e){
var social = e.currentTarget.dataset.social;
popupTools.popup('/auth/'+social+'/', "Authentication", {}, function (err, user) {
if (err) {
console.log(err.message);
return false;
} else {
$rootScope.$broadcast('authenticate', user);
}
});
};
this.logout = function(){
$rootScope.$broadcast('authenticate', null);
};
});
The problem is $scope.$on is called twice printing the log messages twice. Why is that so, I am not able to understand.

Related

access a javascript function in the same 'returned value object'

How do I access a javascript function in the same 'returned value object' and the parent function is unnamed.
here's a code sample
function ($http, $rootScope, $timeout, $location, config, $q, sessionService) {
return {
_get_user_approval_mode: function (data) {
var defer = $q.defer();
this.prepareHttpCall($http, true);
$http.post(config.CLIENT_API_ROOT + 'user-approval-mode', {
params: data
})
.then(function (response) {
defer.resolve(response);
}).catch(function (error) {
if (error_handler(error) === "") { //Getting on this line since error_handler() is undefined
defer.reject(error);
}
});
return defer.promise;
},
error_handler(error) {
console.log('error received in handler');
console.log(error);
if (error.status == "400") {
$('#somethingWrong').modal('show');
$rootScope.errorHandleMessage = error.data.reason;
} else if (error.status == "401" && error.data.message == "Unauthorized" || error.status == "401" && error.data.message == "The incoming token has expired") {
// $('body').removeClass('modal-open');
// $('.modal-backdrop').remove();
$location.path('/login');
} else if (error.status + "".match('5\d{2}')) {
$('#somethingWrong').modal('show');
$rootScope.errorHandleMessage = "Sorry! something went wrong, please try after sometime.";
} else {
return "";
}
return "error handled";
}
}
}
I am getting error of undefined in function '_get_user_approval_mode' when try calling 'error_handler' function - as commented in the above code.
Without knowing how _get_user_approval_mode is called (i.e. without knowing what its this value will be), the "safest" solution is to assign the object to a variable and access that variable:
function ($http, $rootScope, $timeout, $location, config, $q, sessionService) {
var obj = {
_get_user_approval_mode: function (data) {
var defer = $q.defer();
this.prepareHttpCall($http, true);
$http.post(config.CLIENT_API_ROOT + 'user-approval-mode', {
params: data
})
.then(function (response) {
defer.resolve(response);
}).catch(function (error) {
if (obj.error_handler(error) === "") {
defer.reject(error);
}
});
return defer.promise;
},
error_handler(error) {
// ...
}
};
return obj;
}
However, if error_handler doesn't actually have to be a method on the object because it is not called from other code, defining it as a separate function would make more sense.

How to get loggedin user info in angularjs

I want to get info on the currently logged in user so that i can display it for example. I have tried the following code but i get the error AuthService.getAuthMember is not a function can anyone help
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http, $cookies) {
// create user variable
var user = null;
// we must create authMemberDefer var so we can get promise anywhere in app
var authenticatedMemberDefer = $q.defer();
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
getAuthMember: getAuthMember,
setAuthMember: setAuthMember
});
function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}
//this is function that we will call each time when we need auth member data
function getAuthMember() {
return authenticatedMemberDefer.promise;
}
//this is setter function to set member from coockie that we create on login
function setAuthMember(member) {
authenticatedMemberDefer.resolve(member);
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
//**
$cookies.putObject('loginSession', data);
// here create coockie for your logged user that you get from this response, im not sure if its just "data" or data.somethingElse, check you response you should have user object there
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
//on log out remove coockie
$cookies.remove('loginSession');
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
}]);
myApp.controller('meetupsController', ['$scope', '$resource', 'AuthService', function ($scope, $resource, AuthService) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
/AuthService.getAuthMember().then(function(member){
console.log(member);
//here your member should be and you can apply any logic or use that data where u want
$scope.username1=member.username;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.text = $scope.username;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
$scope.username = '';
});
}
}]);
myApp.controller('userController', ['$scope', '$resource', function ($scope, $resource) {
/* var Meetup = $resource('/api/user');
$scope.users = []
Meetup.query(function (results) {
$scope.users = results;
});
*/
var Meetup = $resource('/api/user', {},{
query: {method: 'get', isArray: true}
});
$scope.users = []
$scope.text='mikyas';
Meetup.query({text: $scope.text}).$promise.then(function (results) {
$scope.users = results;
}, function(error) {
// console.log(error);
$scope.meetups = [];
});
}]);
Can you change your run to something like this
myApp.run(function($rootScope, $location, $route, AuthService, $cookies) {
$rootScope.$on('$routeChangeStart',
function(event, next, current) {
if ($cookies.get('loginSession')) {
var session = JSON.parse($cookies.get('loginSession'));
AuthService.setAuthMember(session);
} else {
$location.path('/login');
}
});
});
Also try console.log(AuthService) and check if you see that getAuthMember() function.
Edit:
var myApp = angular.module('myApp', ['ngResource', 'ngRoute', 'ngCookies']);
Don't forget to include angular cookies.

angular spa app not working ngResource

In Angular ngResource is not functionning correctly. I have added the script reference. The problem is that when I add the dependencie to ngResourc blank pages are displayed. What should I do?
/*var app = angular.module('myApp', ['ngResource']);
app.factory('todoFactory', function($resource) {
return $resource('/api/meetups');
});*/
angular.module('myApp').controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
}]);
angular.module('myApp').controller('logoutController',
['$scope', '$location', 'AuthService', '$resource',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
/*
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', create_at: ''};
$scope.afficher = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
*/
$scope.meetups = [];
/*var Meetup = $resource('/api/meetups');
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}*/
}]);
angular.module('myApp').controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
I will add code on demand
It's always better in such cases to open a debug window (F12 or command+shift+I), toggle Console tab and check what it says. Blank page can de displayed within several circumstances.
Also you can try to complete the commented-out version of your code to avoid new module declaration like this^
var app = angular.module('myApp', ['ngResource']);
app.factory('todoFactory', function($resource) {
return $resource('/api/meetups');
});
app.controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
}]);
app.controller('logoutController',
['$scope', '$location', 'AuthService', '$resource',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
/*
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', create_at: ''};
$scope.afficher = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
*/
$scope.meetups = [];
/*var Meetup = $resource('/api/meetups');
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}*/
}]);
app.controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
angular.module('myApp').controller('logoutController',
['$scope', '$location', 'AuthService', '$resource',
function ($scope, $location, AuthService,**$resource**) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
you havent add the resource to your function

AngularJS - Does not test callback function from Service call in controller in unit test script using Jasmine

Error:In test.js call callback(fetch response) from servie function call in controller
Here there is three files.
In that test.js test the controller.js file using karma-jasmin for unit testing for angular js
controller.js
'use strict';
// Login Angular Module Controller
var loginModule = angular.module('loginModule.controllers'['toaster','vcRecaptcha']);
// Controller Function : loginCtrl
// Parameters : $scope, $rootScope, $cookieStore, $location, AuthenticationServiceLogin, FlashService, toaster, vcRecaptchaService, $http, $controller
loginModule.controller('loginCtrl', function ($scope, $rootScope, $cookieStore, $location, AuthenticationServiceLogin, FlashService, toaster, vcRecaptchaService, $http, $controller)
{
//redirect user to dashboard if already logged in
$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$location.path('/home');
}
// Function Name : forget password
$scope.forgetPassword = function(){
$scope.dataLoading = true;
AuthenticationServiceLogin.forgetPassword($scope.email, function (response) {
if (response.success) {
toaster.pop('success', "", "Email sent Successfully. Please check your email.");
$scope.dataLoading = false;
}else{
toaster.pop('error', "", "Email is incorrect / Email not exist in Database");
$scope.dataLoading = false;
}
});
};
//AuthenticationService.ClearCredentials();
// Function Name : login
$scope.login = function (){
$scope.dataLoading = true;
// callback(response);
// Service Calls Function : userLogin
// Parameters : $scope.username,$scope.password AuthenticationServiceLogin.userLogin($scope.username,$scope.password, function (response) {
console.log(response.success);
if(response.success)
{
AuthenticationServiceLogin.SetCredentials(response);
toaster.pop('success', "", "Login Successful");
$location.path('/home');
}
if (response.status ==200) {
//AuthenticationServiceLogin.SetCredentials(response);
//START STOMP to establish connection
var stompCtrl = $rootScope.$new();
$controller('StompController', { $scope: stompCtrl });
//END STOMP to establish connection
toaster.pop('success', "", "Login Successful");
$location.path('/home');
}
else if(response.status ==401){
toaster.pop('error', response.status+" "+response.statusText," Access is denied due to invalid credentials");
$scope.dataLoading = false;
}
else {
toaster.pop('error', "Username / Password", "Username or password is incorrect");
$scope.dataLoading = false;
}
});
};
});
service.js
'use strict';
var loginModule = angular.module('loginModule.services',['vcRecaptcha']);
loginModule.service('AuthenticationServiceLogin', function ($http, $cookieStore,$rootScope,$timeout, UserService, Base64,vcRecaptchaService,ENV) {
var service = {};
var servicePath = ENV.apiEndpoint;
this.forgetPassword = function(email,callback)
{
$timeout(function () {
var response;
if(email == 'admin#belvms.com'){
response = {success: true};
}
else {
response = {success: false};
}
callback(response);
}, 900);
}
this.userLogin = function(username, password,callback) {
$timeout(function () {
var response;
if(username == 'admin' && password =='admin'){
response = {success: true};
}
else {
//response = {success: false, message: 'Username or password is incorrect'};
}
callback(response);
}, 900);
var data1 = "username=" + username + "&password="
+ password + "&grant_type=password&scope=read%20write&" +
"client_secret=belSecret&client_id=vms-bel";
};
this.SetCredentials = function (username, password) {
var authdata = Base64.encode(username + ':' + password);
$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
$cookieStore.put('globals', $rootScope.globals);
}
};
});
test.js
'use strict';
describe('Login', function () {
var $controller1,AuthenticationServiceLogin,$window,$scope,$location;
beforeEach(module('loginModule.controllers'));
beforeEach(inject(function(_$controller_,_$q_,_$window_,_$location_) {
$controller1 = _$controller_;
$window = _$window_;
AuthenticationServiceLogin = { userLogin: function() {},
forgetPassword: function() {}
}; spyOn(AuthenticationServiceLogin,'userLogin').and.returnValue(response);
spyOn(AuthenticationServiceLogin,'forgetPassword').and.returnValue(response);
}));
describe('Login', function () {
it('To call Login function', function () {
var $scope = {};
var $rootscope = {};
var $location = {};
var $cookieStore = {};
var $http = {};
var $controller = {};
var FlashService = {};
var controller = $controller1('loginCtrl',{
$scope: $scope,
$rootscope: $rootscope,
$location: $location,
$window: $window,
$cookieStore:$cookieStore,
AuthenticationServiceLogin: AuthenticationServiceLogin,
FlashService:FlashService,
$http:$http,
$controller:$controller
});
$scope.login();
});
it('To call services', function() {
var $scope = {};
var $rootscope = {};
var $location = {};
var $cookieStore = {};
var $http = {};
var $controller = {};
var FlashService = {};
var controller = $controller1('loginCtrl',{
$scope: $scope,
$rootscope: $rootscope,
$location: $location,
$window: $window,
$cookieStore:$cookieStore,
AuthenticationServiceLogin:AuthenticationServiceLogin,
FlashService:FlashService,
$http:$http,
$controller:$controller
});
$scope.username="admin";
$scope.password="admin";
$scope.login();
it('should have a getData function', function() {
expect(angular.isFunction(AuthenticationServiceLogin.userLogin)).toBe(true);
});
$scope.email='admin#belvms.com';
var response1=function(response){};
console.log(response1);
expect(AuthenticationServiceLogin.userLogin).toHaveBeenCalledWith('admin','admin',response1);
});
});
});
Here i attached image that display error when run test script.
enter image description here
so give solution why this erroe or why can't fetch reponse from userLogin function in test script

Error: $injector:unpr Unknown Provider in AngularJS

I'm trying to do test app on AngularJS but stuck on few days on one place
with this error:
angular.js:38 Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=AuthtokenProvider%20%3C…terceptor%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24compile
as I could understand, I did a mistake somewhere in the references:
can you show me where my code below
mainController.js:
angular.module('mainController', [])
.controller('MainController', function($rootScope, $location, Auth) {
var vm = this;
vm.LoggedIn = Auth.isLoggedIn();
$rootScope.$on('$routeChangeStart', function () {
vm.LoggedIn = Auth.isLoggedIn();
Auth.getUser()
.then(function (data) {
vm.user = data.data;
});
});
vm.doLogin = function () {
vm.processing = true;
vm.error = '';
Auth.login(vm.loginData.username, vm.loginData.password)
.success(function (data) {
vm.processing = false;
Auth.getUser()
.then(function (data) {
vm.user = data.data;
});
if (data.success)
$location.path('/');
else
vm.error = data.message;
});
}
vm.doLogout = function () {
Auth.logout();
$location.path('/logout');
}
});
userController.js:
angular.module('userController', ['userService'])
.controller('UserController', function(User){
var vm = this;
User.all()
.success(function (data) {
vm.users = data
})
})
.controller('UserCreateController', function(User, $location, $window){
var vm = this;
vm.signupUser = function () {
vm.message = '';
User.create(vm.userData)
.then(function(response){
vm.userData = {};
vm.message = response.data.message;
$window.localStorage.setItem('token', response.data.token);
$location.path('/');
})
}
})
authService.js:
angular.module('authService', [])
.factory('Auth', function($http, $q, AuthToken) {
var authFactory = {};
authFactory.login = function(username, password){
return $http.post('/api/login', {
username: username,
password: password
})
.success(function(data){
AuthToken.setToken(data.token);
return data;
})
}
authFactory.logout = function(){
AuthToken.setToken();
}
authFactory.isLoggedIn = function(){
if(AuthToken.getToken())
return true;
else
return false;
}
authFactory.getUser = function(){
if(AuthToken.getToken())
return $http.get('/api/me');
else
return $q.reject({ message: "User has no token"});
}
return authFactory;
})
.factory('AuthToken', function($window){
var authTokenFactory = {};
authTokenFactory.getToken = function(){
return $window.localStorage.getItem('token');
}
authTokenFactory.setToken = function (token) {
if(token)
$window.localStorage.setItem('token', token);
else
$window.localStorage.removeItem('token');
}
return authTokenFactory;
})
.factory('AuthInterceptor', function ($q, $location, Authtoken) {
var interceptorFactory = {};
interceptorFactory.request = function(config){
var token = Authtoken.getToken();
if(token){
config.headers['x-access-token'] = token;
}
return config
};
interceptorFactory.responseError = function (response) {
if(response.status == 403)
$location.path('/login');
return $q.reject(response);
}
return interceptorFactory;
});
userService.js:
angular.module('userService', [])
.factory('User', function($http){
var userFactory = {};
userFactory.create = function(userData){
return $http.post('/api/signup', userData);
}
userFactory.all = function(){
return $http.get('/api/users');
}
return userFactory;
});
app.js:
angular.module('MyApp', ['appRoutes', 'mainController', 'authService', 'userController', 'userService'])
.config(function($httpProvider){
$httpProvider.interceptors.push('AuthInterceptor');
});
app.routes.js:
angular.module('appRoutes', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/views/pages/home.html'
})
.when('/login',{
templateUrl: 'app/views/pages/login.html'
})
.when('/signup', {
templateUrl: 'app/views/pages/signup.html'
});
//$locationProvider.html5Mode(true);
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
You need to inject your authService into your mainController to make it available since you are using Auth in mainController:
angular.module('mainController', ['authService']);
Everytime you pass in the 2nd argument to module (the array) it creates a new module that doesn't have access to other modules that have been created. So you have to make them available to each other this way.
You can read about loading dependencies here
Maybe the problem is referencing the name of the module in different files. I read in another post here that this makes the module to load the number of times it is repetead. So asign a name to a variable and then use the variable in the rest of the files instead of naming it again.
Example of the forum.

Categories

Resources