Error: error:unpr Unknown Provider - angularjs

MY MAIN CONTROLLER
var MyApp = angular.module('ionicApp', ['ionic', 'MobiNav', 'authFactory']);
CONTROLLER CONSUMING FACTORY
MyApp.controller('AuthUser', ['$scope', 'authFactoryService', function ($scope, authFactoryService) {
$scope.showForm = true;
$scope.UserDataLogin = function () {
var loginData = {};
$scope.registration = {
userName: $scope.Auth.userName,
password: $scope.Auth.password,
confirmPassword: $scope.Auth.password
};
authFactoryService.SaveRegistration(registration);
window.scope = loginData;
};
}
]
);
THIS IS THE FACTORY IN SEPERATE FILE
var AuthService = angular.module('authFactory', []);
AuthService.factory('authFactoryService', [
'$http', '$q', '$scope', function ($http, $q, $scope) {
return {
SaveRegistration: function() {
var urlBase = 'http://localhost:48868/';
$http.post(urlBase + 'api/account/register', registration).then(function(response) {
$scope.savedSuccessfully = true;
$scope.message = "User has been registered successfully, you will be redicted to login page in 2 seconds.";
},
function(response) {
var errors = [];
for (var key in response.data.modelState) {
for (var i = 0; i < response.data.modelState[key].length; i++) {
errors.push(response.data.modelState[key][i]);
}
}
$scope.message = "Failed to register user due to:" + errors.join(' ');
});
}
};
}]);
error what i'm getting
Error: [$injector:unpr] http://errors.angularjs.org/1.2.17/$injector/unpr?p0=copeProvider%20%3C-%20%24scope%20%3C-%20authFactoryService
at Error (native)
why it is unable to load authFactoryService service

Finally Figured the dug,
$scope was again injected in Factory
replaced
this
AuthService.factory('authFactoryService', [
'$http', '$q', '$scope', function ($http, $q, $scope) {}]);
to this (just removed the $scope which was again injected in factory for dependency.
AuthService.factory('authFactoryService', [
'$http', '$q', function ($http, $q, $scope) {}]);

var AuthService = angular.module('authFactory', []);
You indlcuded the an empty array in your module. This makes it a
module setter, overwriting an existing module.
to fetch a module you use angular.module('authFactory') <-- note the missing second parameter.
Regards
Sander

Related

Getting the dreaded module not instantiated error, but everything appears right

I'm getting the error: "[$injector:modulerr] Failed to instantiate module myApp due to: ReferenceError: isUndefined is not defined". It suggests I misspelled something or forgot to included dependencies. I've checked and all my scripts are included, all my spelling is correct, and I don't think I've left any dependencies out. I've got a lot of other controllers structured very similarly to this one with no problem, but now two of my most recent added controllers/views are giving me the error. I stripped out all the logic to make sure I wasn't doing something inadvertent, but still no dice. I'm including the module it says is undefined, a similar controller that works, and the controller (now stripped of all logic except a console.log) for the new view that doesn't work. Any ideas?
The "undefined" module (with a number of logic taken out for brevity):
var app = angular.module("myApp", ["ngRoute", 'ngAnimate', 'angular-growl', 'ui.select', 'ngSanitize', 'ui.bootstrap', 'ui.bootstrap.datetimepicker']);
var HeaderCtl = function($scope, $location) {
console.log('inside HeaderCtl : ' + $scope.isLoggedIn);
$scope.tabSelected = function(tabname) {
console.log('Server Parameter :' + $scope.tabname);
$location.path("/" + $scope.tabname);
}
}
app.controller("HeaderCtl", ["$scope", "$location", 'growl', HeaderCtl]);
The similar working controller based on the module:
(function() {
var app = angular.module("myApp");
var loginController = function($scope, $rootScope, $http, $location, myApp, growl) {
// $scope.currenttab = $scope.isLoggedIn;
$scope.sendDt = function() {
$http.post('/login', {
username: $scope.user.username,
password: $scope.user.password,
})
.success(function(user) {
$rootScope.isLoggedIn = 'yes';
console.log('successfully logged in and redirecting to :');
$location.path("/");
$http.get('/getnavlist').success(function(list) {
if (list !== '0') { // got some menus
$rootScope.navlist = list;
$location.path("/" + list[0].value);
}
});
},
function() {
console.log('error in logging in');
$rootScope.message = 'user name or password is wrong';
$location.path("#/welcomeLogin");
});
}
};
app.controller("loginController", loginController);
}());
Finally, the error module with logic stripped out:
(function() {
var app = angular.module("myApp");
var signUpController = function($scope) {
$scope.formModel = {};
console.log("Woomp!");
}
app.controller("signUpController", signUpController);
}());
You can't inject angular module as injectable inside factory function. In loginController you had injected myApp(module name) as a dependency. This is root cause of your problem.
Change
//VVVVV//remove this
var loginController = function($scope, $rootScope, $http, $location, myApp, growl) {
to
var loginController = function($scope, $rootScope, $http, $location, growl) {

Unknown provider error while injecting service

I am trying to inject a custom service to a controller but it give the error that unknown provider. I have attached the relevant code below kindly look in to it as its been a while I am stuck in this problem.I am following coursera's course they are also doing it in the same way but for me its not working.
var app = angular.module('tutorial', ['ngRoute','ngMaterial'])
app.service('myService',
function myService(data) {
var service = this;
service.validator = function(data) {
if (data.name.$valid)
return true
else
return false
}
// return service
}
)
app.controller('myCtrl',['$scope', '$http', '$location', 'myService', myCtrl])
function myCtrl($scope, $http, $location, myService) {
$scope.editorEnabled = false;
myService = this;
$scope.insertemployee = function(empinfo) {
if (myservice.validator(empinfo)) {
console.log(empinfo.name)
console.log(empinfo.email)
console.log(empinfo.address)
$http.post('insertEmp.php',{'name':empinfo.name, 'email': empinfo.email, 'address':empinfo.address}).then(function(data) {
console.log(data)
})
}
}

writing a simple Angular Service

OK, I've built services before but obviously I don't actually know what makes them tick, since I can't seem to debug this ultra-simple service call:
app.js:
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = [];
function dataService() {
console.log("I am the dataService and I am loaded");
var foo = 1;
function getData () {
return 2;
}
}
})();
I see this on-screen: I am Angular and I am working. so Angular is loading.
I see this in console: I am the dataService and I am loaded so the dataService is actually being loaded.
But then the console.log is:
undefined (line 8)
TypeError: dataService.getData is not a function (line 9)
What am I missing?
The previous answers are correct in that your $http injection was wrong, but you are also not attaching your service functions to the service:
function dataService() {
var dataService = this; //get a reference to the service
//attach your functions and variables to the service reference
dataService.foo = 1;
dataService.getData = function() {
return 2;
};
}
An Angular service is very simply an object class. It is also a singleton, meaning it's instantiated only once per run of your app. When the service is instantiated it is very much akin to calling the new operator on your dataService "class":
var $dataService = new dataService();
So, when you inject dataService into your controller, you are actually getting an instance, $dataService, of your dataService "class".
See this blog entry for further reading: https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider-5f426cfe6b8c#.sneoo52nk
You are missing the 2nd parameter $http in the function. The named parameters and the actual parameters in function need to be the same, same order and same number. What happened before is that dataService was being assigned an $http instance and the actual dataService was not injected at all because there was no 3rd parameter to inject it into.
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, $http, dataService) {
// ----was missing-----^
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
We have missed the second param '$http' in function. Just add the '$http' param, it should work fine
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope,$http, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
This is how I've been taught to set up services:
function dataService() {
var dataService = {};
var _foo = 1;
var _getData = function () { return 2; }
dataService.foo = _foo;
dataService.getData = _getData;
return dataService;
}
I believe this facilitates public/private methods/vars.
For reference, this is the full code accessing my service:
app.js:
var gridApp = angular.module('gridApp', []);
// create the controller and inject Angular's $scope
gridApp.controller('mainController', ['$scope', 'dataService', function($scope, dataService) {
// create a message to display in our view
$scope.message = 'Angular is working';
var init = function(){
getPackageData();
};
var getPackageData = function (){
return dataService.getData().then(
function successCallback(response) {
console.log(response);
},
function errorCallback(response) {
console.log(response);
}
);
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = ['$http'];
function dataService($http) {
var dataService = {};
var _getData = function () {
return $http({
method: 'GET',
url: 'data/packages.json'
})
.then(function successCallback(response) {
return response;
},
function errorCallback(response) {
return response;
});
}
dataService.getData = _getData;
return dataService;
}
})();

Angularjs--factory is undefined

I am developing an application using MVC and angularjs and very new to angularjs. The code uses lot of different factory defined in separate js files and those factories are injected correctly in modules but still I see 'factory not defined error'
The app.js is below:-
(function () {
'use strict';
angular.module('MyApp', ['common.core', 'common.ui'])
.run(run);
run.$inject = ['$rootScope', '$location', '$cookieStore', '$http','membershipService'];
function run($rootScope, $location, $cookieStore, $http) {
// handle page refreshes
$rootScope.repository = $cookieStore.get('repository') || {};
if ($rootScope.repository.loggedUser) {
$http.defaults.headers.common['Authorization'] = $rootScope.repository.loggedUser.authdata;
}
}
})();
Factory is defined in separate file like this:-
(function (app) {
'use strict';
var app = angular.module('MyApp');
app.factory('membershipService', membershipService);
membershipService.$inject = ['apiService', 'notificationService','$http', '$base64', '$cookieStore', '$rootScope'];
function membershipService(apiService, notificationService, $http, $base64, $cookieStore, $rootScope) {
var service = {
login: login,
register: register,
saveCredentials: saveCredentials,
removeCredentials: removeCredentials,
isUserLoggedIn: isUserLoggedIn
}
function login(user, completed) {
apiService.post('/api/account/authenticate', user,
completed,
loginFailed);
}
function register(user, completed) {
apiService.post('/signup', user,
completed,
registrationFailed);
}
function saveCredentials(user) {
var membershipData = $base64.encode(user.username + ':' + user.password);
$rootScope.repository = {
loggedUser: {
username: user.username,
authdata: membershipData
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + membershipData;
$cookieStore.put('repository', $rootScope.repository);
}
function removeCredentials() {
$rootScope.repository = {};
$cookieStore.remove('repository');
$http.defaults.headers.common.Authorization = '';
};
function loginFailed(response) {
notificationService.displayError(response.data);
}
function registrationFailed(response) {
notificationService.displayError('Registration failed. Try again.');
}
function isUserLoggedIn() {
return $rootScope.repository.loggedUser != null;
}
return service;
}
})(angular.module('common.core'));
The controller is defined like this:-
(function (app) {
'use strict';
var app = angular.module('MyApp');
app.controller('SignUpController', SignUpController);
SignUpController.$inject = ['$scope', 'membershipService', 'notificationService', '$rootScope', '$location'];
function SignUpController($scope, membershipService, notificationService, $rootScope, $location) {
$scope.pageClass = 'page-login';
$scope.register = register;
$scope.user = {};
};
function register() {
membershipService.register($scope.user, registerCompleted)
}
function registerCompleted(result) {
if (result.data.success) {
membershipService.saveCredentials($scope.user);
notificationService.displaySuccess('Hello ' + $scope.user.username);
$scope.userData.displayUserInfo();
$location.path('/');
}
else {
notificationService.displayError('Registration failed. Try again.');
}
}
})(angular.module('common.core'));
The script are loaded like below:-
bundles.Add(new ScriptBundle("~/bundles/Controllers").Include(
"~/Scripts/Controllers/app.js",
"~/Scripts/Services/apiService.js",
"~/Scripts/Services/notificationService.js",
"~/Scripts/Services/membershipService.js",
"~/Scripts/Services/fileUploadService.js",
"~/Scripts/Controllers/SignUpController.js"
The 'register' function throws an error 'membershipservice not defined', what am i doing wrong? Please help.
I'm seeing this:
run.$inject = ['$rootScope', '$location', '$cookieStore', '$http','membershipService'];
function run($rootScope, $location, $cookieStore, $http) {
// handle page refreshes
You are missing the membershipService in the function parameter list.
Also this:
SignUpController.$inject = ['$scope', 'membershipService', 'notificationService', '$rootScope', '$location'];
function SignUpController($scope, membershipService, notificationService, $rootScope, $location) {
$scope.pageClass = 'page-login';
$scope.register = register;
$scope.user = {};
};
function register() {
membershipService.register($scope.user, registerCompleted)
}
function registerCompleted(result) {
if (result.data.success) {
membershipService.saveCredentials($scope.user);
notificationService.displaySuccess('Hello ' + $scope.user.username);
$scope.userData.displayUserInfo();
$location.path('/');
}
else {
notificationService.displayError('Registration failed. Try again.');
}
}
This will never work, because you are defining the function outside of the function where you pass the membershipService into.
The SignUpController should look something like:
function SignUpController($scope, membershipService, notificationService, $rootScope, $location) {
$scope.pageClass = 'page-login';
$scope.register = register;
$scope.user = {};
function register() {
membershipService.register($scope.user, registerCompleted)
}
function registerCompleted(result) {
if (result.data.success) {
membershipService.saveCredentials($scope.user);
notificationService.displaySuccess('Hello ' + $scope.user.username);
$scope.userData.displayUserInfo();
$location.path('/');
}
else {
notificationService.displayError('Registration failed. Try again.');
}
}
};
See, in your method SignUpController that is where the DI will be injecting the parameters into.
However, you have defined the functions that require those parameters OUTSIDE the scope of SignUpController function

Angular - DI dependency injection the connection between different Modules and service\directive from another module

If I need a to use a factory from another module do I need to add first the DI of the module to my current module and after that add the DI of the factory to the current factory? Or can I just add the factory itself (without its module)?
So if above its true the only use of Di in modules is for that use... or am i missing something else?
var myApp = angular.module('myApp', []);
myApp.service('myService', function() {
// do some stuff
});
myApp.controller('otherCtrl', function($scope, myService) {
// do some stuff
});
inject myApp module into otherApp module and use service myService:
var otherApp = angular.module('otherApp', ['myApp']);
otherApp.controller('myCtrl', function($scope, myService) {
$scope.myService = myService;
});
declare modules with dependecies.
var baseApp = angular.module("ERMSApp", ['ngSanitize', 'ngRoute', 'ngTable']);
var baseApp1 = angular.module("ERMSApp1", ['ERMSApp', 'ngSanitize', 'ngRoute', 'ngTable']);
declaring service.
baseApp.factory("getEmployeesService", function ($http) {
var promise;
var getEmployeesService = {
getEmployees: function () {
if (!promise) {
var promise = $http.get("/Timesheet/GetEmployees").then(function (result) {
return result;
});
}
return promise;
}
}
return getEmployeesService;
});
using service in another module
baseApp1.controller("leaveOnBehalfCtrl", function ($scope, $http, $filter, $sce, ngTableParams, $compile, getEmployeesService) {
getEmployeesService.getEmployees().then(function (data) {
$scope.employees = data.data;
})
});

Resources