Making a Session service available to my SessionsController in AngularJS - javascript

This is probably a matter of me not handling dependency injection proper, but I'm trying to make a 'Session' service available to my SessionsController. Here's my SessionsController:
angular.module('App.controllers').controller('SessionsController', ['$scope', '$location', '$cookieStore', 'Session', function($scope, $location, $cookieStore, Session) {
$scope.foo = function() {
console.log("clicked foo..");
}
$scope.session = Session.userSession;
$scope.create = function() {
if ( Session.signedOut ) {
$scope.session.$save()
.success(function(data, status, headers, config) {
$cookieStore.put('_app_user', data);
});
}
};
$scope.destroy = function() {
$scope.session.$destroy();
};
}]);
Here's the actual Session service definition:
angular.module('App.services').service('Session',[ '$cookieStore', 'UserSession', 'UserRegistration', function($cookieStore, UserSession, UserRegistration) {
this.currentUser = $cookieStore.get('_app_user');
this.signedIn = !!$cookieStore.get('_app_user');
this.signedOut = !this.signedIn;
this.userSession = new UserSession( { email:"foo#bar.com", password:"example", remember_me:true } );
//this.userRegistration = new UserRegistration( { email:"foo-" + Math.floor((Math.random()*10000)+1) + "#bar.com", password:"example", password_confirmation:"example" } );
$rootScope.$on('$routeChangeStart', function (current, next) {
if (this.signedOut && next !== '/login') {
console.log("relocating user..");
//$location('/login');
}});
}]);
And here's how I strung it together:
angular.module('App.resources', ['ngResource']);
angular.module('App.services', ['ngResource']);
angular.module('App.directives', []);
angular.module('App.filters', []);
angular.module('App.controllers', ['ngCookies', 'Session']);
var App = angular.module("App", ['App.resources', 'App.services', 'App.directives', 'App.filters', 'App.controllers', 'ui.compat', '$strap.directives', 'templates']);
Clearly missing something to string everything together as Firebug is complaining that there is no module named: Session.

Firebug is right, you have no module named session. You have a service named Session in the App.services module.
Just remove the Session module injection, and you are good to go.
angular.module('App.controllers', ['ngCookies']);

Related

unable to inject a service in controller

I am using requireJS for my angularjs app.
common.service.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.config(['$provide', function ($provide) {
$provide.factory("CommonService", CommonService);
}]);
CommonService.$inject = ["$http", "$q", "$window"];
function CommonService($http, $q, $window) {
var service = {};
service.sharedValue;
return service;
}
});
page1.controller.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
// Q2: common service
$scope.commonService = CommonService;
}]);
});
Now When I am running my app, it throws me below error:
Error: [$injector:unpr] Unknown provider: CommonServiceProvider <- CommonService <- Page1Controller
any inputs?
Your core module should have empty dependencies injected
var coreModule = angular.module('coreModule',[]);
Also in page1. controller you dont have to declare the module again, you can just use
angular.module('coreModule')
.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
Define config
Define the service
Define the controller, inject the service, use the dependency in function declaration etc. As you would know, both are needed, after all you need the those handles, else what's the point in injecting.
Define a module, define module dependencies. NOTE that the service has to be defined before controller. If you reverse the order, you will get an error, probably that's what is happening here. Without full code, I can't tell.
bootstrap angular.
Finally working plunkr: http://plnkr.co/edit/CE9enkgW3KASx8pf5vdb?p=preview
define('config',[],function(){
function config($routeProvider) {
$routeProvider.when('/home', {templateUrl: 'tpl.home.html', controller: 'HomeController'})
.otherwise({redirectTo: '/home'});
}
config.$inject=['$routeProvider'];
return config;
});
define('dataSvc',[], function(app){
function factoryFunc ($q, $timeout){
var svc = {getData: getData};
return svc;
function getData() {
console.log('executing function');
var d = $q.defer();
$timeout(function(){
console.log("firing timeout");
d.resolve({name:"test", data:[1, 2, 3, 4]});
}, 750);
return d.promise;
}
}
factoryFunc.$inject=['$q', '$timeout'];
return factoryFunc;
});
define('HomeController',[], function() {
function HomeController($scope, dataSvc) {
$scope.name = "Mahesh";
dataSvc.getData().then(function(result){
$scope.data=result;
console.log($scope.data);
});
}
HomeController.$inject=['$scope','dataSvc'];
return HomeController;
});
define('coreModule', ['config', 'dataSvc', 'HomeController']
, function(config, dataSvc, HomeController){
var app = angular.module('app', ['ngRoute','ngResource']);
app.config(config);
app.factory('dataSvc',dataSvc);
app.controller('HomeController', HomeController);
});
require(['coreModule'],
function() {
angular.bootstrap(document, ['app']);
}
);
Refer also,
https://www.sitepoint.com/using-requirejs-angularjs-applications/
http://beletsky.net/2013/11/using-angular-dot-js-with-require-dot-js.html

AngularJs: use cookies inside custom service

I tried to use angular cookies in custom service, but got the error:
Unknown provider: ngCookiesProvider <- ngCookies <- checkLoginService
I store module, controllers and services in separate files.
Controller:
(function() {
'use strict';
angular
.module('app')
.controller('AuthController', AuthController);
AuthController.$inject = ['$scope', '$http', '$location', 'checkLoginService'];
function AuthController($scope, $http, $location, checkLoginService) {
/* jshint validthis:true */
var vm = this;
vm.title = 'AuthController';
$scope.login = function(user) {
/*logic*/
}
$scope.checklogin = function () {
if (checkLoginService.checkLogin()) {
/*logic*/
}
}
$scope.checklogin();
}
})();
Service:
(function () {
'use strict';
angular
.module('app')
.service('checkLoginService', ['ngCookies', checkLoginService]);
checkLoginService.$inject = ['$http'];
function checkLoginService($http, $cookies) {
return {
checkLogin: function () {
/*logic*/
}
}
}
})();
ngCookies is module not a dependency name, you should inject ngCookies in module dependency and use $cookies to get cookie object
//somewhere in app.js
angular.module('app', ['otherModules', ..... , 'ngCookies'])
Also add $cookies missing dependency inside a checkLoginService $inject array.
angular.module('app')
.service('checkLoginService', ['$cookies', checkLoginService]);
checkLoginService.$inject = ['$http', '$cookies'];
function checkLoginService($http, $cookies) {
return {
checkLogin: function () {
/*logic*/
}
}
}

10 digest() iteration reached error in login procedure

This is my code to implement in my application a login procedure. The application has to verify the cookie set by the server and continue with the login procedure by redirect the user to canvas state. My issue is that I get the above mentioned error. Actually it works that is the login is made successfully but I would like to get rid of this error. I guess that the error should be in the $stateChangeStart but I don't know how to fix it. any idea?
(function() {
'use strict';
angular
.module('app', [
'ui.router',
'ngResource',
'ngCookies',
'app.login'
])
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/login');
})
.run(function($rootScope, AuthService, RedirectService) {
$rootScope.$on('$stateChangeStart', function(event, toState) {
if (!AuthService.isAuthenticated()) {
// the user isn't authenticated
event.preventDefault();
// redirect to the server side
RedirectService.redirectToAuth();
}
});
});
})();
(function() {
'use strict';
angular
.module('app.login')
.factory('AuthService', Auth);
Auth.$inject = ['Cookie', 'Session'];
function Auth(Cookie, Session) {
return {
login: function(params) {
// here set the session with params passed by the server
Session.create(params.id, params.data.id, params.data.make, params.data.name);
},
isAuthenticated: function() {
// check cookie here set in the server side
return Cookie.exist();
}
};
}
})();
(function() {
'use strict';
angular
.module('app.login')
.service('Cookie', Cookie);
Cookie.$inject = ['$cookies'];
function Cookie($cookies) {
this.authCookie = $cookies.__cookie;
this.exist = function() {
return (this.authCookie ? true : false);
};
}
})();
(function() {
'use strict';
angular
.module('app.login')
.factory('RedirectService', Redirect);
Redirect.$inject = ['$window'];
function Redirect($window) {
return {
redirectToAuth: function() {
// redirect the user to the server for auth
$window.location.href = "http://" + $window.location.host + "/auth/facebook";
}
};
}
})();
(function() {
'use strict';
angular
.module('app.login')
.controller('LoginController', Login);
// here inject what function Login needs
Login.$inject = ['$rootScope', '$scope', '$state', '$stateParams', 'AuthService'];
function Login($rootScope, $scope, $state, $stateParams, AuthService) {
var params = {
id: $stateParams.userid,
data: {
id: $stateParams.modelid,
make: $stateParams.modelmake,
name: $stateParams.modelname
}
};
$scope.login = function(params) {
AuthService.login(params);
// activate the canvas state
$state.go('canvas');
};
// run the login function to set the Session user with data passed by the server
$scope.login(params);
}
})();
Maybe this can help a little more:
/*
We are using the below urlRouterProvider.otherwise() because of:
https://github.com/angular-ui/ui-router/issues/600
*/
$urlRouterProvider.otherwise(function($injector, $location) {
var $state = $injector.get('$state');
$state.go('login');
});
With this code you can still use the otherwise(), the disadvantage of using when() is that other unknown routes will not match. Above code solved all of our infinite loops.
Fixed the issue
$urlRouterProvider.otherwise('/login');
caused all this issue.
removed it and replaced with when() solved the issue

angular factory not available

angular.module('pipelineChromeApp', [
'ngResource',
'ngSanitize',
'ngRoute',
'LocalStorageModule'
])
angular.module('pipelineChromeApp')
.factory('Profile', [
'$http',
'apiUrl',
'localStorageService',
function ($http, apiUrl, localStorageService) {
var baseUrl = apiUrl + 'profile.json?api_key=';
return {
login: function(apiKey) {
return $http.get(baseUrl + apiKey);
},
logout: function() {
localStorageService.clearAll();
localStorageService.set('loggedIn', false);
console.log("cleared local storage");
return true;
}
}
}]);
angular.module('pipelineChromeApp')
.controller('LoginController', [
'$scope',
'Profile',
'$location',
function ($scope, Profile, $location) {
$scope.apiKey = "";
$scope.login = function(){
debugger
// Profile.login().then({
// $location.path( "/actions" );
// });
};
}]);
For some reason Profile isn't available in LoginController. Have I loaded things wrong?
As you mentioned in your comment, the problem you have is in the console, and I assume the browser you're using is chrome. In chrome/v8, the javascript engine tries very hard to optimize your code, it will remove any unused function parameters. In your case, Profile isn't used anywhere in your function, so v8 has removed it.
That's also the reason why it works fine when you have some code to do with the Profile.
Usually I will add a console.log() to an empty function if I want to check some variables in the chrome console, like this:
$scope.login = function() {
debugger;
console.log(Profile);
};

Error: Unknown provider: SessionProvider <- Session AngularJS

I am aware that the error which is in the title of this question is basically because in my controller I am injecting a Session service in my controller that has not been defined. I am currently looking at: Angular Devise for which I am rolling out in an application that is using rails but have angular and rails separate. My setup on the angular side is as followed:
main.js
angular.module('App.controllers', []);
angular.module('App.config', []);
angular.module('App.directives', [])
angular.module('App.resources', ['ngResource']);
angular.module('App.services', []);
var App = angular.module("App", [
"ngResource",
"ngCookies",
"$strap.directives",
"App.services",
"App.directives",
"App.resources",
"App.controllers",
"TotemApp.config"
], function ($routeProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "/login";
return;
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
});
Session.js
App.service('Session',[ '$cookieStore', 'UserSession', 'UserRegistration', function($cookieStore, UserSession, UserRegistration) {
this.currentUser = function() {
return $cookieStore.get('_angular_devise_user');
}
this.signedIn = function() {
return !!this.currentUser();
}
this.signedOut = function() {
return !this.signedIn();
}
this.userSession = new UserSession( { email:"sample#email.com", password:"password", remember_me:true } );
this.userRegistration = new UserRegistration( { email:"sample#email.com", password:"password", password_confirmation:"password" } );
}]);
sessions_controller
App.controller('SessionsController', ['$scope', '$location', '$cookieStore', 'Session', function($scope, $location, $cookieStore, Session) {
$scope.session = Session.userSession;
$scope.create = function() {
if ( Session.signedOut ) {
$scope.session.$save().success(function(data, status, headers, config) {
$cookieStore.put('_angular_devise_user', Session.userSession.email);
$location.path('/todos');
});
}
};
$scope.destroy = function() {
$cookieStore.remove('_angular_devise_user');
$scope.session.$destroy();
};
}]);
routes.js
'use strict';
App.config(function($routeProvider, $httpProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main/home.html',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'views/sessions/new.html',
controller: 'SessionsController'
})
.when('/sign_up', {
templateUrl: 'views/registrations/new.html',
controller: 'RegistrationsController'
})
.otherwise({
redirectTo: '/'
});
});
This error occurs when I try to access the login page or register page. If someone can shed some light that would be greatly appreciated. Not entirely sure how to resolve this Error: Unknown provider: $SessionProvider <- $Session error
At first glance this looks correct. I can only assume that perhaps you've not included Session.js in your index.html file?
Angular clearly doesn't know what 'Session' service is so there's something wrong there either file not loaded, not loaded correctly or something along those lines as far as I can see.
Edit: Does the error say 'SessionProvider <- Session' or '$SessionProvider -< $session' because if it's the latter, then something is named wrong somewhere in your app since your service is named 'Session' not '$Session'.
When you have syntax error in other javascript or typescript files. You will get the same error. Please make sure that you have no syntax error.

Categories

Resources