Simple angular service not working - javascript

I am trying to create an angular service but it is not working. I have tried numeros things and looked all over.Please help
//service
angular
.module('RDash')
.factory('googleLogin', googleLogin);
function googleLogin()
{
this.testFunc = function ()
{
console.log("THIS IS A TEST SERVICE");
}
};
Below: tryoing to call service test func
//controller
angular
.module('RDash')
.controller('ComposeCtrl', ['$scope','$rootScope','$http','googleLogin', ComposeCtrl]);
function ComposeCtrl($scope, $rootScope, $http, googleLogin) {
console.log("ComposeCTRL active");
googleLogin.testFunc(); // this doesnt work, error: "main.min.js:2 Error: [$injector:undef] http://errors.angularjs.org/1.5.8/$injector/undef?p0=googleLogin"
I feel like the issue is with injecting i just dont know where. Please help thanks

Factory needs to return the function refrence and you need to declare variable testFunc (answer to why here):
Update working snippet.
angular.module('RDash', []);
angular
.module('RDash')
.factory('googleLogin', googleLogin);
function googleLogin() {
var testFunc = function() {
console.log("THIS IS A TEST SERVICE");
}
return {
testFunc : testFunc
}
};
angular
.module('RDash')
.controller('ComposeCtrl', ['$scope', '$rootScope', '$http', 'googleLogin', ComposeCtrl]);
function ComposeCtrl($scope, $rootScope, $http, googleLogin) {
console.log("ComposeCTRL active");
googleLogin.testFunc();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="RDash" ng-controller="ComposeCtrl"></div>
angular
.module('RDash')
.factory('googleLogin', googleLogin);
function googleLogin() {
var testFunc = function() {
console.log("THIS IS A TEST SERVICE");
}
return {
testFunc: testFunc
}
};

Related

calling public method from another js function inside service

I created custom service
(function () {
"use strict";
angular
.module("common.services")
.factory("redirectService",
["$q", "$location",
redirectService])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('redirectService');
});
function redirectService($q, $location){
...
var redirect = function() {
...
};
return {
doRedirect: redirect
};
}
inside my other controller where I'm injecting this redirectService I'm trying to call this publish doRedirect method
angular
.module("myModule")
.controller("MyController",
["$scope",
"redirectService"
MyController]);
function MyController(redirectService){
vm.doClick = function() {
redirectService.doRedirect();
}
}
Here I'm getting error on calling doRedirect method
Error: redirectService.doRedirect is not a function
You have an imbalance of number of arguments in dependency array and function arguments for MyController
Change
function MyController(redirectService){
To
function MyController($scope, redirectService){
MyController function has two arguments first $scope, second redirectService
angular
.module("myModule")
.controller("MyController",
["$scope",
"redirectService"
MyController]);
function MyController($scope, redirectService){
vm.doClick = function() {
redirectService.doRedirect();
}
}

AngularJS - I don't understand why factory is always undefined

I defined a factory that makes a get request but when I inject it in a controller it always throws an undefined error.
This is the factory:
(function() {
'use strict';
var app = angular
.module('myApp');
app.factory('homeFactory', homeFactory);
function homeFactory ($q, $http, $location) {
var data = {};
data.getProducts = getProducts;
function getProducts() {
return $http.get('http://localhost:8000/api/v1/products')
.error(errorMessage);
}
function errorMessage(response) {
console.log('There was an error', response);
}
return data;
}
})();
This is the controller:
(function() {
'use strict';
var app = angular
.module('myApp');
app.controller('homeController', homeController);
homeController.$inject =[homeFactory];
function homeController(homeFactory) {
var home = this;
homeFactory.getProducts()
.success(success);
function success(jsonData, statusCode) {
console.log('The request was successful', statusCode);
console.dir(jsonData);
home.products = jsonData;
}
}
})();
It appears to be ok, but the console throws:
Uncaught ReferenceError: homeFactory is not defined
The problem is in your DI annotation. You should only use strings
homeController.$inject = ['homeFactory'];
See https://docs.angularjs.org/guide/di#-inject-property-annotation
The $inject property is an array of service names to inject.
The controller function supports dependency injection. You don't need to use the $injector directly. Try this:
var app = angular
.module('myApp');
app.controller('homeController', homeController);
function homeController(homeFactory) {
var home = this;
homeFactory.getProducts()
.success(success);
function success(jsonData, statusCode) {
console.log('The request was successful', statusCode);
console.dir(jsonData);
home.products = jsonData;
}
}
The angular runtime will find the homeFactory service, and automatically pass it to your controller function when it's called.
In controller you shall put factory in dependecies
app.controller('homeController', ['homeFactory', '$scope',
function (homeFactory, $scope){
//scope code goes here
}]
);

TypeError: api.getAll is not a function, service method is not recognized

I have a very simple service and a controller attempting to get some information from it, but I keep getting .methodName is not a function.
Here is the service, apiService.js :
(function (module) {
function api() {
var sharedService = {};
sharedService = {
getAll: function () {
return 'test';
}
};
return sharedService;
}
module.factory("api", api);
}(angular.module("anbud")));
Then I attempt to use my method getAll in the controller, like this:
(function () {
'use strict';
angular.module('anbud')
.controller('BasicExampleCtrl', ['$scope', 'api', function (api, $scope) {
// on successfull request
function onJson(json) {
$scope.data = json;
}
// error getting json
function onError() {
throw 'error getting json';
}
function initialize() {
api.getAll()
.then(onJson, onError);
}
initialize();
}]);
}());
But I get the error:
TypeError: api.getAll is not a function
at initialize (basic-example.js:67)
Any help is appreciated thank you.
You have interchanged the dependencies sequence inside controller factory function, the sequence must be same as they are included in DI array while injecting in function.
Code
.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope, api) { //<- first $scope then api.
try it like this:
.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope,api) {

Cannot read property 'ClearCredentials' of undefined

I'm new to angularjs an i'm trying to create a login form but i'm getting following error :
Cannot read property 'ClearCredentials' of undefined.
I have used some tutorial stuff. But now i started to create an application from scratch. But i'm stuck with the AuthenticationService.js
This is what i have done
app.js
(function(angular) {
angular.module("app.directives", []);
angular.module("app.AuthenticationService", []);
angular.module("app.controllers", []);
angular.module("app", ['ngRoute','ngResource','routes','app.directives','app.controllers',"app.AuthenticationService"]);
}(angular));
controller.js
//LoginController
(function (angular) {
var LoginController = function($scope,$location,AuthenticationService){
var vm = this;
//todo vm.login = login;
(function initController() {
// reset login status
// calling function from AuthenticationService
AuthenticationService.ClearCredentials();
})();
/* TODO: This has not been tested yet
function login(){
vm.dataLoading = true;
// constructor from AuthenticationService
AuthenticationService.Login(vm.username,vm.password, function(response){
//Check if method respons === success
if (response.success) {
// calling function from AuthenticationService
AuthenticationService.SetCredentials(vm.username, vm.password);
$location.path('/');
} else {
// use function from FlashService
// FlashService.Error(response.message);
// vm.dataLoading =false;
}
});
}*/
}
LoginController.$inject = ['$scope','$location'];
angular.module("app.controllers").controller("LoginController", LoginController);
}(angular));
AuthenticationService.js
(function (angular) {
var AuthenticationService = function($http, $cookieStore, $rootScope, $timeout, UserService) {
var service = {};
service.ClearCredentials = ClearCredentials;
function ClearCredentials() {
$rootScope.globals = {};
$cookieStore.remove('globals');
$http.defaults.headers.common.Authorization = 'Basic ';
}
return service;
}
AuthenticationService.$inject = ['$http', '$cookieStore', '$rootScope', '$timeout', 'UserService'];
angular.module("app.AuthenticationService").factory("AuthenticationService", AuthenticationService);
})(angular);
If you have suggestions for this code please let me also know.
You inject two parameters:
LoginController.$inject = ['$scope','$location'];
But then you refer to the third one. Isn't this a problem?
Check if the inline version would work:
angular.module("app.controllers").controller("LoginController", funtion($scope,$location,AuthenticationService){
...
}
If it does, then there is an issue with Angular injection.

myfunction() function call from one controller to another in angularjs

i have used Angularjs and i wanna call getcustomer function from one controller to another controller i have so many doing gooogling but i don't have an idea that how to call that
i have write below code which i used
var app = angular.module('Napp', []);
app.controller('GetAlphabetical', function ($scope, $http) {
function getCutomers() {
$scope.loading = true;
$http.get('#Url.Content("~/Home/GetPesrons")').then(function (response) {
//var _data = angular.fromJson(response);
$scope.loading = false;
$scope.Customer = response.data; // please check the request response if list id in data object
}, function (error) {
throw error;
})
}
});
and second controller :
app.controller('MainCtrl', function ($scope, $http) {
getCutomers()
});
Mate, you will have to follow the following steps to resolve your problem. Firstly you have you create a factory
angular
.module('Napp')
.factory('CustomerFactory', ['$http', function ($http) {
var _factory = {};
_factory.getCustomers = function () {
return $http.get('#Url.Content("~/Home/GetPesrons")');
};
return _factory;
}]);
Then you can share data and functions between multiple controllers or services
GetAlphabetical Controller :
angular
.module('Napp')
.controller('GetAlphabetical', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {
loadCustomers();
function loadCustomers() {
CustomerFactory.getCustomers().then(function (successResponse) {
$scope.Customer = successResponse.data; // please check the request response if list id in data object
}, function (errorResponse) {
throw error;
})
}
}]);
MainCtrl Controller :
angular
.module('Napp')
.controller('MainCtrl', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {
loadCustomers();
function loadCustomers() {
CustomerFactory.getCustomers().then(function (successResponse) {
$scope.Customer = successResponse.data; // please check the request response if list id in data object
}, function (errorResponse) {
throw error;
})
}
}]);
This can be easily done by defining it as a service and injecting it as a dependency.
var app = angular.module('myApp', []);
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
app.controller('MainCtrl', function ($scope, $http, helloWorldFromService) {
app.controller('GetAlphabetical', function ($scope, $http, helloWorldFromService) {
Angular Service
What you want to do is to somehow communicate between two controllers. This can be easily be achieved using $broadcast & $on.
Incase there is a parent child relation between your controllers, use the following.
function firstCtrl($scope){
$scope.$broadcast('someEvent', [1,2,3]);
}
function secondCtrl($scope){
$scope.$on('someEvent', function(event, mass) {console.log(mass)});
}
If there is no parent child relationship between your controller, then inject $rootScope and broadcast using that.
related question - https://stackoverflow.com/a/14502755/1182982

Categories