main module can't read my service - javascript

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

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

Cannot read propery getRiders of undefined

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)

Why my Angular factory throw TypeError: __tracer.traceFunCall(...) is not a function

This line of code does no let me sleep:
$scope.search = function (login) {
github.getUser(login).then(onUserResponse, onError);
};
Loading it up:
angular.module('lol')
.factory('github', github);
Returning two functions :
return {
getUser: getUser,
getRepos: getRepos
};
With this siganture:
var github = function ($http) {
Consumed by MainController:
var MainCtrl = function ($scope, github, $filter, $timeout, $intervel, $anchorScroll, $location) {
And not injected into it's dependencies:
MainCtrl.$inject = ['$scope', '$filter', '$interval', '$timeout', '$anchorScroll', '$location'];
With the app being loaded like this:
angular.module('lol', [])
.controller('MainCtrl', MainCtrl);
And all of this throw: TypeError: __tracer.traceFunCall(...) is not a function
i think you missed githubas second parameter in MainCtrl.$inject = ['$scope', 'github'...
also updated your jsbin here
code organization was complicating situation more than necesary.
Also from the looks of it you tried to do two modules quick example how it should be done here.

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.

Unknown scope provider $scope

I am trying to inject $scope but it's not working. This is my code:
var appCtrl = app.controller(
'AppCtrl',
function ($scope, $resource, $location, $route, sharedProperties) {}
);
appCtrl.prepData = function (
$q, $scope, $resource, $location, $route, sharedProperties) {}
I am trying to define a function after getting the appCtrl variable. But $scope wouldn't work there. Any idea how to resolve this issue?

Categories