Unknown provider error while injecting service - angularjs

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

Related

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;
}
})();

Issue with Angular.js and Angular Style Guide

I'm having an issue correctly getting a data service to work as I try to follow the Angular Style Guide (https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#data-services)
I'm sure it's something obvious to the more experienced but I can't get the data set to assign properly to the vm.items outside of the
Data Service
(function() {
'use strict';
angular
.module('portfolioApp')
.factory('portfolioService', portfolioService);
portfolioService.$inject = ['$http', 'logger'];
function portfolioService($http, logger) {
return {
getPortfolioData: getPortfolioData,
};
function getPortfolioData() {
return $http.get('./assets/portfolio/portfolioItems.json')
.then(getPortfolioDataComplete)
.catch(getPortfolioDataFail);
function getPortfolioDataComplete(response) {
return response.data;
}
function getPortfolioDataFail(error) {
logger.error('XHR Failed for getPortfolioData.' + error.data);
}
}
}
}());
Controller
.controller('portfolioController', ['$scope', '$http', '$stateParams', 'logger', 'portfolioService', function($scope, $http, $stateParams, logger, portfolioService) {
var vm = this;
vm.items = [];
activate();
function activate() {
return getData().then(function() {
logger.info('Activate the portfolio view');
});
}
function getData() {
return portfolioService.getPortfolioData()
.then(function(data) {
vm.items = data;
return vm.items;
});
}
console.log("test")
console.log(vm.items);
console.log("test")
}])
Your getData function is a promise, so it's run asynchronously. Your console.log are called before the end of the promise so the vm.items is still empty.
Try to put the log in the then callback.

Error: error:unpr Unknown Provider

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

Creating a service around Restangular in AngularJS is not returning array

I am new to AngularJS and Restangular. But being a good citizen I thought I would try to create some services.
While this works and I get an array back populating a drop down list:
Restangular.all('/ta/tas').getList().then(function(tas) {
$scope.therapyAreas = tas;
});
But when I create a service, and then inject the service into the controller I get nothing back:
.controller('prGPTCtrl',['$scope', 'prTAService', 'Restangular', function($scope, prTAService, Restangular) {
$scope.prGpts = {};
$scope.therapyAreas = {};
Restangular.setBaseUrl('resources/pr');
$scope.therapyAreas = prTAService.prTAList();
Service:
prServices.factory('prTAService', ['Restangular', '$q', function prTAService(Restangular, $q) {
return {
prTAList : function(therapyAreas) {
var therapyAreas = {};
Restangular.setBaseUrl('resources/pr');
Restangular.all('/ta/tas').getList().then(function(tas) {
therapyAreas = tas;
return therapyAreas;
}
);
}
};
}]);
I see it being called in Chrome Debugger...I suspect it is related to promises (which I don't really "get").
Update:
This works as a service:
prServices.factory('prTAService', ['Restangular', '$q', function prTAService(Restangular, $q) {
return {
prTAList : function(therapyAreas) {
Restangular.setBaseUrl('resources/pr');
return Restangular.all('/ta/tas').getList();
}
};
}]);
And this works when calling it, not sure what I am gaining here!
prTAService.prTAList().then(function(tas) {
$scope.therapyAreas = tas;
});
The service needs to return the promise and the controller will handle the return because this is asynchronous. You are doing it right in the last part there:
prTAService.prTAList().then(function(tas) {
$scope.therapyAreas = tas;
});

Angularjs and qunit testing

I have a angularjs web application and want to use qunit for unit testing in it. I have a controller:
function RootCtrl($scope, $rootScope, $window, $location) {
// logger is empty at the start
$scope.logger = '';
// we have no login error at the start
$scope.login_error = '';
//
// Get values array of object
//
$rootScope.values = function (obj) {
var vals = [];
for( var key in obj ) {
if(key !== '$$hashKey' && key !== 'checked')
vals.push(obj[key]);
}
return vals;
}
}
Now i want to write unit test for values function with qunit. I included all js files to the test/index.html and qunit.css. Now my test.js has following content:
var injector = angular.injector(['ng', 'myApp']);
var init = {
setup : function () {
this.$scope = injector.get('$rootScope').$new();
}
}
module('RootCtrl', init);
test('RootCtrl', function(){
var $controller = injector.get('$controller');
$controller('RootCtrl', {
$scope : this.$scope,
$location : this.$location
});
equal(['value'], $controller.values({'key' : 'value'}))
});
But i'm getting error: http://docs.angularjs.org/error/$injector/unpr?p0=$rootElementProvider%20%3C-%20$rootElement%20%3C-%20$location%20%3C-%20$route at:
$controller('RootCtrl', {
$scope : this.$scope,
$location : this.$location
});
How to inject correctly controller and use $scope, $rootScope, $location and another services from it?
Thank you.
Try this instead of your controller
$controller('RootCtrl',['$scope', '$rootScope', '$location','$route', function ($scope, $rootScope, $location, $route) {
$scope : this.$scope,
$location : this.$location
}]);
Had similar problem, so since no other answer here.
I ended up using:
client side code:
var myApp= angular.module('myApp', []);
myApp.controller('myCtrl', function ($scope) {
//angular client side code
$scope.canSubmit = function () {
//some logic
return true;
}
}
Qunit tests:
var ctrl, ctrlScope, injector;
module("Testing the controller", {
setup: function () {
angular.module('myApp');
injector = angular.injector(['ng', 'myApp']);
ctrlScope = injector.get('$rootScope').$new();
ctrl = injector.get('$controller')('myCtrl', { $scope: ctrlScope });
ctrlScope.model = {
//model object
};
},
teardown: function () {
}
});
test("Given something happened then allow submit", function () {
ok(ctrlScope.someFunction(...), "some functionality happened");
equal(true, ctrlScope.canSubmit());
});
This blog post was useful.
One can easily inject more into the controller under test.

Resources