Error: Unknown provider: SessionProvider <- Session AngularJS - javascript

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.

Related

Angularfire ngRoute/resolve issue, jumps to otherwise

I'm using the latest Angular + Firebase and trying to set up a login authorization system. I have home.html which contains login+signup links, going to login.html and adding credentials works just fine (logging correct UID when submittet) but it's supposed to route to dash.html but goes back to home.html.
I've figured out that it seem to be issues with my resolve functions because the problem disappears when I remove .otherwise. But I still want (need?) it there I think.
If I'm logged in (but redirected to home.html) I can still access dash.html through the URL and I cannot access it again if I use the logout function at dash.html and that's how it should be.
But I can't figure out why I'm redirected to home.html in the first place.
Here's some of the code, any help appreciated:
My .run, .config and routes.
app.run(['$rootScope', '$location',
function($rootScope, $location){
$rootScope.$on('$routeChangeError',
function(event, next, previous, error){
if(error === 'AUTH_REQUIRED'){
$location.path('/home');
}
});
}]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider,
$locationProvider){
$routeProvider
.when('/home', {
templateUrl: '/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: '/login.html',
controller: 'loginController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$waitForAuth();
}]
}
})
.when('/dash', {
templateUrl: '/dash.html',
controller: 'dashController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$requireAuth();
}]
}
})
.otherwise({ redirectTo: '/home' });
}]);
My login controller:
app.controller('loginController', ['currentAuth', '$scope', '$firebaseAuth',
'Auth', '$location', '$rootScope',
function(currentAuth, $scope, $firebaseAuth, Auth, $location, $rootScope){
var ref = new Firebase('https://url.firebaseio.com');
$scope.auth = $firebaseAuth(ref);
$scope.loginUser = function(){
$scope.auth = Auth;
$scope.auth.$authWithPassword({
email:$scope.email,
password:$scope.password
}, {
remember: 'sessionOnly'
}).then(function(authData) {
console.log('Logged in as: ', authData.uid);
$scope.auth.$onAuth(function(authData) {
$rootScope.auth = true;
$scope.auth = Auth;
$location.path('/dash.html');
})
}).catch(function(error) {
console.log('There was an error: ', error);
});
};
}]);
And my factory and module:
var app = angular.module('app', ['firebase', 'ngRoute']);
app.factory('Auth', ['$firebaseAuth',
function($firebaseAuth){
var ref = new Firebase('https://url.firebaseio.com');
return $firebaseAuth(ref);
}]);
it has with your resolve issue.
If you look at the documentation firebase doc
you will see that they use the
$waitForSignIn
or
$requireSignIn
functions. I know that because I have done the same thing. Try that instead and it should work

angular unknown provider error using factory and ui.router resolve

I'm getting unknown provider error when i'm trying to use resolve from a state. The object i want returned seems to be returned correctly, so i can't really figure out what the problem is.
This is my first angular project so if I something seems wierd it probably is.
The error: https://docs.angularjs.org/error/$injector/unpr?p0=boardProvider%20%3C-%20board%20%3C-%20AppCtrl
var ponk = angular.module("ponk", ["ui.router", "ngResource"]);
ponk.config(['$stateProvider', '$urlRouterProvider',
"$locationProvider", function ($stateProvider, $urlRouterProvider,
$locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider.state('board', {
url: '/b/:slug',
templateUrl: 'views/board.html',
controller: "AppCtrl",
controllerAs: "pk",
resolve: {
board: function($stateParams, boardFactory) {
var board = {};
if($stateParams.slug) {
board = boardFactory.get({slug:$stateParams.slug}).$promise;
}
return board;
}
}
});
}]).run(function($state) { $state.go('board'); });;
ponk.factory("boardFactory", ["$http", "$resource",
function($http, $resource) {
return $resource('/board/:slug', {slug:'slug'}, {update: { method: "PUT" }});
}]);
ponk.controller("AppCtrl", ["$scope", "$http", "boardFactory", "board",
function($scope, $http, boardFactory, board ) {
console.log(board); // correct object, but error
}]);
EDIT:
discovered the above code works. The problem is when i add this to the controller:
var pk = this;
var pk.board = board;

How do you add a service in Angular so a controller can use it?

I have a basic angular setup. I want to add another factory service so that the mainCtrl can use it.
Here is my controller.js
angular.module('Manalator.controllers', [])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Here is my services.js
angular.module('Manalator.services', [])
.factory('cordovaReady', [function () {
return function (fn) {
var queue = [],
impl = function () {
queue.push([].slice.call(arguments));
};
document.addEventListener('deviceready', function () {
queue.forEach(function (args) {
fn.apply(this, args);
});
impl = fn;
}, false);
return function () {
return impl.apply(this, arguments);
};
};
}])
.factory('manaFactory', [function(){
this.testString = function(){
return 'This works';
};
}]);
Here is my routes.js
angular.module('Manalator', ['ngRoute', 'Manalator.services', 'Manalator.controllers'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/main.html'
})
.when('/devotion', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/devotion.html'
})
.when('/results', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/results.html'
})
.otherwise({redirectTo: '/'});
});
I get the following error:
TypeError: Cannot read property 'testy' of undefined
at new <anonymous> (controllers.js:3)
at Object.i [as invoke] (main.min.js:1)
at $get.f.instance (main.min.js:2)
at m (main.min.js:1)
at s (main.min.js:1)
at $get.e (main.min.js:1)
at main.min.js:1
at p.$get.p.$eval (main.min.js:3)
at p.$get.p.$apply (main.min.js:3)
at main.min.js:1
It is a cordova phonegap setup with basic routes. I am new to angular. I have looked over the internet and im having trouble setting up a basic service to hold all my data so i can access it from all my routes. Any help would be appreciated.
You will need to identify your services as a dependency of the controller.
The first step is to make sure you define the services before the controller.
then change the controller code so that it names the services as a dependency.
angular.module('Manalator.controllers', ['Manalator.services'])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Hope this helps!

AngularJS cannot find provider

I'm getting an unknown provider error trying to use a service in a factory. When I push the factory into the interceptor, the console logs the error:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- authService <- authInterceptor <- $http <- $templateRequest <- $compile
I'm thinking that authService is not ready yet but it's not clear to me how to create it so that it is. Can you explain the correct way to use the authService in the factory?
app.js
angular.module('app', [
'ngResource',
'ngRoute',
'ui.calendar',
'calendarControllers',
'accountControllers',
'commonControllers',
'commonServices'
]).
constant('API', 'http://127.0.0.1:8000').
config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/cal.html',
controller: 'CalCtrl'
})
.when('/account', {
templateUrl: '/account.html',
controller: 'AccountCtrl'
})
.otherwise({
templateUrl: '/login.html'
});
}
]);
services.js
'use strict';
angular.module('commonServices', []).
factory('authInterceptor', ['API','authService',
function (API, auth) {
return {
request: function(config) {
var token = auth.getToken();
if(config.url.indexOf(API) === 0 && token) {
config.headers.Authorization = 'JWT ' + token;
}
return config;
},
// If a token was sent back, save it
response: function(res) {
if(res.config.url.indexOf(API) === 0 && res.data.token) {
auth.saveToken(res.data.token);
}
return res;
}
}
}
]).
config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
}).
service('authService', ['$scope', '$window',
function ($scope, $window) {
$scope.saveToken = function(token) {
$window.localStorage['jwtToken'] = token;
};
$scope.getToken = function() {
return $window.localStorage['jwtToken'];
};
$scope.logout = function() {
$window.localStorage.removeItem('jwtToken');
};
}
]);
You could not access $scope inside service, that is why your service initialization has been stopped, and app thrown $scope provider array.
service('authService', ['$window', function($window){
//..code here..
}])

Common route resolver in angularjs?

I am using route resolver in angularjs,for user will be redirect to login if user is not logged in as follows,
$routeProvider
.when('/', {
templateUrl: 'app/components/main/dashboard.html',
controller: 'dashboardController',
resolve: {
login: function ($rootScope, $location) {
if (!$rootScope.currentUser) {
$location.path('/login');
}
}
}
})
Here I want use this login function in many other routes,So i can copy paste same resolve function to every where as follows,
.when('/items', {
templateUrl: 'app/components/item/list.html',
controller: 'itemController',
resolve: {
login: function ($rootScope, $location) {
if (!$rootScope.currentUser) {
$location.path('/login');
}
}
}
})
It is working fine,my question is,is there any way to avoid this duplication of codes or is there any other better method ?
I set up a github repository yesterday which is a starting point for a web app and contains this feature here
If you look in public/app/app-routes.js you will see I have added resolve functions as variables, then you can simply do this rather than writing a whole function each time:
Function
var checkLoggedIn = function($q, $timeout, $http, $window, $location, $rootScope) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') {
$rootScope.loggedInUser = user;
$window.sessionStorage['loggedInUser'] = JSON.stringify(user);
deferred.resolve();
}
// Not Authenticated
else {
$window.sessionStorage['loggedInUser'] = null;
$rootScope.loggedInUser = null;
deferred.reject();
$location.url('/login');
}
});
return deferred.promise;
};
checkLoggedIn.$inject = ["$q", "$timeout", "$http", "$window", "$location", "$rootScope"];
Route
.when('/profile', {
title: 'Profile',
templateUrl: '/app/templates/profile.html',
controller: 'ProfileController',
resolve: {
loggedIn: checkLoggedIn
}
})
Should be easily adaptable for your app. Hope that helps!

Categories

Resources