Cannot read propery getRiders of undefined - javascript

I want to call a service which I defined in DeliverService but when I called it from controller it gives an error of Cannot read propery getRiders of undefined , NO idea why this happened :|
DeliverService.js
angular.module('Deliver')
.service('DeliverService', ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService", function($http, $state, $resource, $q, SettingService, $localStorage, MessageService) {
var service = {
getRiders : function(){
return $http.get("Hero.json");
//return $http.get(SettingService.baseUrl + "api/orders");
} }
return service;
}]);
DeliverCtrl.js
use strict';
angular.module('Deliver').controller('DeliverCtrl',['$scope','$state', "SettingService","DeliverService", function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){
});
}]);

Your dependencies aren't in the matching order here. Hence, DeliverService isn't actually injected.
Your controller code should look something like this:
angular.module('Deliver').controller('DeliverCtrl',
['$scope','$state', '$ionicModal', 'MessageService', 'SettingService','DeliverService',
function($scope, $state, $ionicModal, MessageService, SettingService, DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){});
}]);

In DeliverCtrl.js
The injection Parameter and function parameters do not match
It should be like this
['$scope','$state','$ionicModal','MessageService','SettingService','DeliverService', function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService)

Related

Reusing of functions which is defined between controllers

i would like to reuse the code defined between the controllers
.controller('GenericController', ['$scope', '$controller', '$rootScope', '$dialogs', '$state', '$http', '$modal', '$q', '$timeout', 'projectFactory', 'projectPromise', 'phaseFactory', 'buFactory', 'stakeholderGroupFactory', 'ldapFactory', 'genericFactory', 'User',
function ($scope, $controller, $rootScope, $dialogs, $state, $http, $modal, $q, $timeout, projectFactory, projectPromise, phaseFactory, buFactory, stakeholderGroupFactory, ldapFactory, genericFactory, User) {
$scope.testing = function() {
console.log("Hello");
};
}]);
You can use the factory and create the object for the function to reuse it.
app.factory("sample",function(){
return function() {
console.log("Hello");
};
})
else collating multiple common functions
app.factory("commonFunctions",function(){
commonFunction1(){
console.log("common func1")
}
commonFunction2(){
console.log("common func2")
}
return {
commonFunction1: commonFunction1,
commonFunction1: commonFunction2
};
})
Used the $controller for the importing this fixed my issue

Ionic factory undefined

Newbie in Ionic and Angular.
I am trying to develop a test app and trying to use the factory function.
I did the design from Ionic Creator and trying to add my coding in to it.
Below is my controller file.
angular.module('app.controllers', [])
.controller('loadingCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams, awesomeFactory) {
$scope.aa = awesomeFactory.GetUser();
}])
.controller('mainPageCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams) {
}])
.controller('historyCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams) {
}])
.controller('firstrunCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams) {
}])
.controller('resultsCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams) {
}])
.controller('doctorCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams) {
}])
.controller('bookingCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams) {
}])
.controller('appointmentCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams) {
}])
Below is my file that has the factory.
angular.module('app.services', [])
.factory('BlankFactory', [function(){
}])
.service('BlankService', [function(){
}]
.factory('awesomeFactory', function($http) {
return {
GetUser: function() {
return $http.get("http addy return json object").then(function(response) {
//Process Stuff Here
return response;
});
},
}
})
);
I am getting 2 errors.
1. Error: awesomeFactory is undefined.
2. TypeError: (intermediate value).factory is not a function[Learn More]
I just don't know what I am doing wrong. Probably something small.
But any help is greatly appreciated.
Thank you in advance.
This is because here in this code
.controller('loadingCtrl', ['$scope', '$stateParams',
function ($scope, $stateParams, awesomeFactory) {
$scope.aa = awesomeFactory.GetUser();
}])
First you will have to do factory injection then try to create its instance
Try this
.controller('loadingCtrl', ['$scope', '$stateParams','awesomeFactory',
function ($scope, $stateParams, awesomeFactory) {
$scope.aa = awesomeFactory.GetUser();
}])

Service undefined when injected into controller

I have a controller that I have injected a factory into but it comes back as undefined when I call a method on that factory. Not sure what I am doing wrong here. Any help would be appreciated.
Factory:
(function(){
'use strict';
// Declare factory and add it 'HomeAutomation' namespace.
angular.module('HomeAutomation').factory('AuthenticationService', ['$http','$localStorage', '$window', function($http, $localStorage, $window){
var service = {};
service.login = Login;
service.logout = Logout;
service.parseJWT = parseJWT;
service.loginStatus = loginStatus;
return service;
function Login(email, password, callback){
$http.post('api/user/login', {email: email, password: password})
.success(function(res){
// Login successful if there is a token in the response.
if(res.token){
// store username and token in local storage to keep user logged in between page refreshes
$localStorage.currentUser = { email: email, token: res.token };
// add jwt token to auth header for all requests made by the $http service
$http.defaults.headers.common.Authorization = 'Bearer ' + res.token;
callback(true);
}else{
callback(res);
}
}).error(function(err){
console.log(err);
});
}
function Logout(){
$localStorage.currrntUser
}
function parseJWT(token){
var base64URL, base64;
base64URL = token.split('.')[1];
base64 = base64URL.replace('-', '+').replace('_', '/');
console.log(JSON.parse($window.atob(base64)));
}
function loginStatus(){
if($localStorage.currentUser){
return true;
}else{
return false;
}
}
}]);}());
Controller:
(function(){
angular.module('HomeAutomation')
.controller('loginController', ['$scope', '$location', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
$scope.isLoggedIn = AuthenticationService.logout();
$scope.logUserIn = function(){
AuthenticationService.login($scope.login.email, $scope.login.password, function(result){
if(result === true){
$location.path('/');
}else{
console.log(result);
}
});
};
$scope.logUserOut = function(){
AuthenticationService.logOut();
}
}]);}());
This is the line that is causing the err:
$scope.isLoggedIn = AuthenticationService.logout();
Apparently "AuthenticationService" is undefined. Not sure why.
Thanks in advance.
You messed up with depedency sequence, you need to remove $localStorage from controller factory function since $localStorage isn't use anywhere in controller & haven't injected in DI array.
.controller('loginController', ['$scope', '$location', 'AuthenticationService',
function($scope, $location, AuthenticationService){
//^^^^^^^^^^removed $localStorage dependency from here
NOTE: Always make sure when you inject any dependency in DI array, they should used in same sequence in controller function
The injection is not good :
.controller('loginController', ['$scope', '$location', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
Try with this :
.controller('loginController', ['$scope', '$location', '$localStorage', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
I don't know which builder you use, but for example with Gulp, you can use gulp-ng-annotate that will do the job for you so that you can only write :
.controller('loginController', function($scope, $location, $localStorage, AuthenticationService){
without the array. The ng-annotate will take care of the rest.

main module can't read my service

I'm trying to call a function which is in a service I have made. Whenever I try to search a username, I get an error which says "cannot read 'getUser' of undefined.
It shouldn't be undefined, I'm passing it an argument of a username it should be able to use. I can't seem to find out what's wrong with my service!
http://plnkr.co/edit/k4FD4eFuVKNvjEwKx2gs?p=preview
Any help to move forward with this would be appreciated :)
(function(){
var github = function($http){
var getUser = function(username){
$http.get("https://api.github.com/users/" + username)
.then(function(response){
return response.data; //still returns a promise
});
};
//angular invokes this, return an object which is github service
var getRepos = function(user){
$http.get(user.repos_url).then(function(response){
return response.data;
});
};
return {
getUser: getUser,
getRepos: getRepos
};
};
var module = angular.module("firstapp"); //get reference to existing module, NOT creating a new one
//register service with angular
module.factory("github", github);
}());
script.js
var app = angular.module("firstapp", []) //defining module, no dependencies (so far)
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
$scope.search = function(username) {
$log.info("Searching for "+username);
//the first parameter to .then is only invokes onusercomplete if the get is successful
//if error, it goes to second parameter which provdes error details
github.getUser(username)
.then(onUserComplete, onError);
if (countdownInterval){
$interval.cancel(countdownInterval);
$scope.countDown = null;
}
};
Problem lies in bad sequence of dependency injection arguments.
It is:
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github)
Should be:
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location","$http", function(
$scope,github,$interval, $log, $anchorScroll, $location, github,$http)
Parameters must be in correct order in DI.
If you encounter errors like:
"cannot read function name of undefined"
Then you should look for function calls and see what's wrong with object from which call goes.
In this case it's something wrong with github.
The issue is in your controller definition you don't have your dependencies line up
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
your dependencies are:
"$scope", "github", "$interval", "$log", "$anchorScroll", "$location"
but they are getting injected as
$scope, $http, $interval, $log, $anchorScroll, $location, github
You have to have the order line up otherwise you'll have the wrong dependency in the wrong variable, also you're not adding $http in your listed dependencies.
Your problem is in the getUser function. You are not returning a promise there. To work the way you are using it it should look like
var getUser = function(username){
return $http.get("https://api.github.com/users/" + username);
};
EDIT1
In your code, you were not returning a promise but the data returned by the promise.
Furthermore, you were returning that data from an anonymous callback (your function(response) {...}) to its caller (in your case then(...)
EDIT2
You should also check the way you are injecting your dependencies
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
should be
.controller("MainController", ["$scope", '$http', "$interval", "$log", "$anchorScroll", "$location", "github", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
EDIT3
You should also change the getRepos method like we did for the other one from
var getRepos = function(user){
$http.get(user.repos_url).then(function(response){
return response.data;
});
to
var getRepos = function(user){
return $http.get(user.repos_url);
});

Using Angular services to hold commonly required data

I am currently writing my first application in Angular and have been very much enjoying all the framework has to offer so far. Like most newbies I set off building everything into a main controller, copying the tutorials. I am now seeing the error of my ways and refactoring.
My question is about services holding data that is commonly required among controllers.
I've now taken the data out of the 'main controller' and placed it into a service that I have injected into both controllers requiring access. Now though neither controller sees the functionality I've defined in the new service:
varianceService is not defined
Being new to this approach i welcome all and any help, aswell as help with my current problem, any comments on the best way to apply this approach would also be highly appreciated.
Thanks in advance.
Here is an example of the code:
var app = angular.module(
'VarianceAnalysis', ['ngRoute', 'ngAnimate', 'mgcrea.ngStrap', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.dateParser', 'SharedServices']
)
.service('varianceService', function () {
var variances = {};
return {
redirect: function (path) {
$location.path(path);
},
getHttpVariances: function (month1, month2) {
var url = "/Home/GetVariances?month_1=";
url += month1;
url += "&month_2="
url += month2;
url += "&forwardBilling=true"
$http.get(url).success(function (data) {
variances = data;
return data;
});
return {};
},
getVariances: function () {
return variances;
}
};
})
.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/MainPage', {
templateUrl: 'mainpage.html',
controller: 'MainPageCtrl'
}).
when('/Variance/:type', {
templateUrl: 'variance.html',
controller: 'VarianceCtrl'
}).
otherwise({
redirectTo: '/MainPage'
});
}])
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', 'varianceService', function ($scope, $http, $location) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
The problems lies in the bracket notation of injecting services in your function..
What you inject in the bracket notation must also be present in the function definition..
e.g.
controller('MyCtrl', ['$scope', '$http', 'varianceService', function($scope, $http, varianceService) {
}]);
so in relation to your code above.. it should be like this..
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', '$http', '$location', 'varianceService', function ($scope, $http, $location, varianceService) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
just as how you have ordered the injected services in your bracket notation, it must also pertain the same order in your function definition.
Change this
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
to
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])

Categories