AngularJS cannot find provider - javascript

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..
}])

Related

Can pass login page with wrong password/username AngularJS

If type the username or password once wrong and change manually the URL to my home GUI, I get access to it without any authentication.
I can't explain why :/
this is my app.js, where all the routing happens and a fiddle with my controller and my html data :
(function() {
'use strict';
// declare modules
angular.module('Authentication', []);
angular.module('Home', ['naif.base64', 'ngFileSaver']);
//dependecies of the module
angular.module('JMeterGui', ['Authentication','Home','ngRoute', 'ngCookies'])
//configure the module
.config(config)
//configure the start of the module
.run(run);
//dependencies of the config module
config.$inject = ['$routeProvider', '$locationProvider', '$qProvider'];
//configure routing depends on the actual URL
function config($routeProvider, $locationProvider, $qProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'modules/home/views/home.html'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'modules/authentication/views/login.html'
})
.otherwise({ redirectTo: '/login' });
}
//dependecies of the run module
run.$inject = ['$rootScope', '$location', '$cookies', '$http'];
function run($rootScope, $location, $cookies, $http) {
// keep user logged in after page refresh
$rootScope.globals = $cookies.getObject('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata;
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in
var restrictedPage = $.inArray($location.path(), ['/login']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
})()
my fiddle with controller and html
Anyone knows why ?
Try to add:
if (restrictedPage && !loggedIn) {
//Prevent default
event.preventDefault();
$location.path('/login');
}

AngularJS: Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- productService

I have created a Service to pull data from database using Web API controller method. But whenever I inject the service and call the service method in controller, it shows the following error:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- productService
http://errors.angularjs.org/1.5.8/$injector/unpr?p0=copeProvider%20%3C-%20%24scope%20%3C-%20productService
Tried a lot but cannot understand where the wrong actually lies!
Here is My AngularJS Module Code:
var app = angular.module("Demo", ["ngRoute"])
Here is my RouteConfig
app.config(function($routeProvider, $locationProvider) {
$routeProvider.when("/products/details/:id",
{
templateUrl: "Temaplates/details.html",
controller: "productDetailsController"
})
})
Here is My Service:
app.factory('productService',
function($scope, $http, $routeParams) {
return {
getDataById: function() {
alert("Hello I am invoked");
$http({
method: "GET",
url: "http://localhost:43618/api/Products",
params: { id: $routeParams.id }
})
.then(function(response) {
$scope.product = response.data;
})
}
};
});
Here is my AngularJS Controller
app.controller("productDetailsController", function ($scope, $http, $routeParams, $location, productService) {
$scope.message = "Product Details";
$scope.product = productService.getDataById();
})
Where is the wrong actually!! Any Help Please!!
There are several things which I wanted to note down
You can't inject $scope inside service
You should return $http.get promise from service method to get data inside controller.
Inside controller use .then to retrieve data from service function.
Factory
app.factory('productService',
function($http, $routeParams) {
return {
getDataById: function() {
//return proimise from here
return $http.get("http://localhost:43618/api/Products", {
params: { id: $routeParams.id }
});
}
};
});
Controller
app.controller("productDetailsController", function($scope, $http, $routeParams, $location, productService) {
$scope.message = "Product Details";
productService.getDataById().then(function(response){
$scope.product = response.data;
}, function(error){
console.log("Error occured ", error);
});
});
You can't inject $scope into a service as specific scopes are only available in directives and components. You can only use $rootScope
This actually makes sense because a service is a singleton. When injected into multiple controllers, which $scope should angular use then? $rootScope on the other hand is also a singleton so that works.

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;

Yeoman: AngularJS & facebook SDK, page not loading

So im new with Angular and i downloaded the Yeoman scaffolding for Angular.JS to fiddle with it a bit.
I'm trying to implement Facebook Login with this library: https://github.com/pc035860/angular-easyfb
Nothing is loading and the console doesnt reflect anything. I'm almost sure the problem has something to do with the injecting of the facebook dependency on the controller.
I have this on my main.js file:
angular.module('circeApp', ['ezfb'])
.controller('MainCtrl', function($scope, ezfb, $window, $location) {
updateLoginStatus(updateApiMe);
$scope.login = function(){
ezfb.login(function(response){
if(response.authResponse){
updateLoginStatus(updateApiMe);
}
}, {scope: 'email,user_likes'});
};
$scope.logout = function(){
ezfb.logout(function(){
updateLoginStatus(updateApiMe);
});
};
function updateLoginStatus(more){
ezfb.getLoginStatus(function(response){
$scope.loginStatus = response;
(more || anular.noop)();
});
}
function updateApiMe(){
ezfb.api('/me', function(response){
$scope.apiMe = response;
});
}
});
And this on my app.js file:
'use strict';
angular.module('circeApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ezfb'
])
.config(function ($routeProvider, $locationProvider, $httpProvider, ezfbProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'partials/login',
controller: 'LoginCtrl'
})
.when('/signup', {
templateUrl: 'partials/signup',
controller: 'SignupCtrl'
})
.when('/settings', {
templateUrl: 'partials/settings',
controller: 'SettingsCtrl',
authenticate: true
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
// Intercept 401s and redirect you to login
$httpProvider.interceptors.push(['$q', '$location', function($q, $location) {
return {
'responseError': function(response) {
if(response.status === 401) {
$location.path('/login');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
}]);
})
.run(function ($rootScope, $location, Auth) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$routeChangeStart', function (event, next) {
if (next.authenticate && !Auth.isLoggedIn()) {
$location.path('/login');
}
});
//Configure ezfb provider aqui
ezfbProvider.setInitParams({
appId: 'XXXXXXXXXXXX',
status: true,
cookie: true,
xfbml: true
});
});
Before this, the page rendered but console told me: "Argument 'MainCtrl' is not a function, got undefined". I fixed a missing parenthesis and made sure ezfb was included in angular.module. Now, the only thing i get is a blank page.

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