Angular.js Service function undefined - javascript

I'm having a controller and servise (I will post all of controller and service code because I have no idea what could be wrong) :
Controller:
'use strict';
app.controller('membersController', ['$scope', 'membersService', function($scope, membersService) {
$scope.members = [];
$scope.updatedMembers = [];
membersService.getMembers().then(function (results)
{
$scope.members =results.data;
},
function(error) {
alert(error.data.message);
});
$scope.update = function () {
membersService.updateMembers($scope.updatedMembers).then(function(results) {
alert(results);
},
function(results) {
alert(results);
});
};
$scope.updateActive = function(member) {
if ( !isInArray($scope.updatedMembers,member))
{
$scope.updatedMembers.push(member);
}
};
var isInArray = function(array, item) {
var found = false;
for (var i = 0; i < array.length; i++) {
if (array[i].id == item.id) {
found = true;
break;
}
}
return found;
};
}]);
Service:
'use strict';
app.factory('membersService', ['$http', 'ngAuthSettings', function ($http, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
var membersServiceFactory = {};
var _getMembers = function () {
return $http.get(serviceBase + 'api/members').then(function (results) {
return results;
});
};
var _updateMembers = function(updatedMembers) {
$http.post(serviceBase + 'api/Members/UpdateMembers', updatedMembers, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(
function (results) {
return results;
},
function(results) {
return results;
});
};
membersServiceFactory.getMembers = _getMembers;
membersServiceFactory.updateMembers = _updateMembers;
return membersServiceFactory;
}]);
This is error that i'm getting in firebug:
Error:
membersService.updateMembers(...) is undefined
$scope.update#http://localhost:37272/Controllers/membersController.js:16:13
$a.prototype.functionCall/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:172:370
fc[c]</<.compile/</</<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:189:395
Yd/this.$get</h.prototype.$eval#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:108:471
Yd/this.$get</h.prototype.$apply#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:109:230
fc[c]</<.compile/</<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:189:370
ne/c/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:31:30
q#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:7:363
ne/c#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:31:14
Can anyone at LEAST point me to the right direction as i'm new in angular.js. Also i would like to notice that request is passed to .net webapi even with this error

If in controller you want to use it like a promise object, I mean:
$scope.update = function () {
membersService.updateMembers($scope.updatedMembers).then(function(results) {
alert(results);
},
function(results) {
alert(results);
});
};
then you should return promise object, $http get method itself is returning promise.
'use strict';
app.factory('membersService', ['$http', 'ngAuthSettings', function ($http, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
var membersServiceFactory = {};
var _getMembers = function () {
return $http.get(serviceBase + 'api/members');
};
var _updateMembers = function(updatedMembers) {
$http.post(serviceBase + 'api/Members/UpdateMembers', updatedMembers, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });;
};
membersServiceFactory.getMembers = _getMembers;
membersServiceFactory.updateMembers = _updateMembers;
return membersServiceFactory;
}]);

Related

Function is not recognized by another function in angularjs

During loading of the partial Html with controller, my function named $scope.actionViewVisitors() is recognized and runs without errors. But whenever I use it inside another function on the same controller, it gives me an error:
TypeError: $scope.actionViewVisitors is not a function. Please see my code below:
angular.module("Visitor.controller", [])
// ============== Controllers
.controller("viewVisitorController", function ($scope, $rootScope, $http, viewVisitorService, viewAccountService, DTOptionsBuilder) {
$scope.visitorList = null;
$scope.viewAccountDetail = null;
$scope.avatar = null;
$scope.visitorDetail = null;
$scope.visitorBtn = "Create";
$scope.actionViewAccount = function () {
$scope.actionViewAccount = viewAccountService.serviceViewAccount()
.then(function (response) {
$scope.viewAccountDetail = response.data.account;
$scope.avatar = "../../avatars/" + response.data.account.AccountId + ".jpg";
})
}
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withDisplayLength(10)
.withOption('bLengthChange', false);
// THIS ONE IS NOT RECOGNIZED
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}
// I DON'T GET ANY ERROR HERE
$scope.actionViewVisitors();
$scope.actionViewAccount();
$scope.createVisitor = function () {
$scope.statusMessage = null;
if ($scope.visitorBtn == "Create") {
$scope.createVisitor = viewVisitorService.serviceCreateVisitor($scope.visitorDetail)
.then(function (response) {
if (response.data.response == '1') {
bootbox.alert({
message: "Successfully created a new visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
} else if (response.data.response == '0') {
bootbox.alert({
message: "Failed in creting visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
}
});
debugger;
$scope.visitorDetail = undefined;
// I GET THE ERROR WHEN I CALL THIS METHOD
$scope.actionViewVisitors();
}
}
})
// ============== Factories
.factory("viewVisitorService", ["$http", function ($http) {
var fac = {};
fac.serviceViewVisitors = function () {
return $http({
url: '/Visitor/ViewVisitors',
method: 'get'
});
}
fac.serviceCreateVisitor = function(visitor) {
return $http({
url: '/Visitor/CreateVisitor',
data: { visitor: visitor },
method: 'post'
});
}
return fac;
}])
You are overwriting the function with Promise in the following line, thus the error is correct
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
Remove $scope.actionViewVisitors =
$scope.actionViewVisitors = function () {
viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
On the first call to the function you are changing it from a function to a Promise. Maybe you want to be returning the result instead?
$scope.actionViewVisitors = function () {
return viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}

Provider 'UserApi' must return a value from $get factory method

In my factory..
var UserService = angular.module('UserService', []);
UserService.factory('UserApi', function ($http) {
var baseUrl = "http://localhost:59844/api";
var UserApi = {};
UserApi.getUsers = function () {
return $http.get(baseUrl + '/UserLogins');
};
});
And in my controller:
var myApp = angular.module('MyApp', ['ngRoute','UserService']);
myApp.controller('HomeController', function ($scope, UserApi) {
getUsers();
function getUsers(){
UserApi.getUsers.success(function (users) {
$scope.users = users;
}).error(function (error) {
$scope.status = "Couldn't load data";
})
}
});
It seems UserApi doesn't return any value. But cannot get it why?
You need to return the service object also
var UserService = angular.module('UserService', []);
UserService.factory('UserApi', function ($http) {
var baseUrl = "http://localhost:59844/api";
var UserApi = {};
UserApi.getUsers = function () {
return $http.get(baseUrl + '/UserLogins');
};
return UserApi;
});

angularjs rewrite controller without factory

i'm developing an app that received from a server a JSON array and divided data in a specific way, i've a portion of code that works if i use it alone but if i tried to insert it in an application it doesn't work.
This is my code:
ionicApp.controller('DefaultController', DefaultController)
.factory('dataService', dataService);
DefaultController.$inject = ['dataService', '$http'];
function DefaultController(dataService, $http) {
var vm = this;
console.log("Dentro ctrl");
getEvents();
function getEvents() {
console.log("Dentro getEvents");
return dataService.getEvents()
.then(function (data) {
console.log("data: " + data);
vm.data = data;
console.log("vm.data: " + vm.data);
return vm.data;
});
}
vm.submit = function (){
console.log("funzione");
console.log(vm.form);
var data = vm.form; // IMPORTANT
//console.clear();
var link = 'http://localhost/<path>/api/apiDoFix.php';
var mail = window.localStorage.getItem("mail");
var scelta = window.localStorage.getItem("scelta");
console.log(data);
console.log ("EMAIL" + mail);
console.log ("SCELTA" + scelta);
$http.post(link, {giorno: data.giorno, ora: data.ora, mail: mail, scelta: scelta})
.then(function (res){
console.log("Dentro http.post");
var response = res.data;
if (response != 'F'){
console.log("Dentro if");
console.log(response);
//window.location.href ="/#/main";
} else {
console.log("Dentro else");
}
});
};
}
dataService.$inject = ['$http'];
function dataService($http) {
console.log("qua");
var service = {
getEvents: getEvents
};
return service;
function getEvents() {
console.log("qua2");
var config = {
transformResponse: function (data, headers) {
var result = {
events: [],
schedules: []
};
var events = JSON.parse(data);
var dates = [];
console.log("qua3");
for (var i = 0; i < events.length; i++) {
if (dates.indexOf(events[i].day) === -1) {
var date = events[i].day;
dates.push(date);
result.events.push({
date: date
});
}
result.schedules.push({
date: events[i].day,
time: events[i].time
});
}
console.log("result: " + result);
return result;
}
};
return $http.get('http://localhost/ShuttleFIX/api/apiTimes.php', config)
.then(getEventsCompleted)
.catch(getEventsFailed);
function getEventsCompleted(response) {
console.log("response " + response.data);
return response.data;
}
function getEventsFailed(error) {
console.error(error);
}
}
}
is it possible to rewrite this code in a controller function without using factory?
Thank's

How do I populate a scope with a http response?

The problem I have is that on page load the response from the API takes a while and my view (scope) is empty. But when I switch view back and forth the groups-view (scope) is updated with the object which was loaded from the API on page load.
I want to be able to load all my data and have it available in all views at all time and for it to dynamically update the first view (scope) on page load when the data becomes available.
I guess this is possible, but what am I missing?
My service:
angular.module('myApp.services', [])
.service('groups', function ($http) {
var groups = [];
// Load the data once from the API
if(!groups.length) {
$http.get('/api/groups')
.then(
function(response) {
groups = response.data;
}
);
}
return {
// For update if new data is available
setData: function(arr) {
groups = arr;
},
// Return all groups
getAll: function () {
return groups;
},
// Get a given group name
getNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].name;
}
}
return null;
},
// Get a given group short name
getShortNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].short_name;
}
}
return null;
},
getTeamsById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].team_ids;
}
}
return null;
}
};
});
My controller:
function GroupsOverviewCtrl($scope, groups) {
// Populate the scope with data
$scope.groups = groups.getAll();
}
GroupsOverviewCtrl.$inject = ['$scope', 'groups'];
The "Angular way" of dealing with async operations is promises instead of callbacks.
This is what it might look like:
.factory('groups', function ($http, $q) {
var groups = [],
return {
setData: function(arr) {
groups = arr;
},
getAll: function () {
if(groups.length) {
return $q.when(groups);
} else {
return $http.get('/api/groups').then(function (response) {
groups = response.data;
return groups;
});
}
},
getNameById: function (id) {...},
getShortNameById: function (id) {...},
getTeamsById: function (id) {...}
};
});
function GroupsOverviewCtrl($scope, groups) {
groups.getAll().then(function (data) {
$scope.groups = data;
});
}
GroupsOverviewCtrl.$inject = ['$scope', 'groups'];
Ok, so I think I've fixed it... getting late here and my brain is shutting down.
The answer was to use a callback (as always with http request).
The service:
angular.module('myApp.services', [])
.factory('groups', function ($http) {
var groups = [],
groupsObj = {
setData: function(arr) {
groups = arr;
},
getAll: function () {
return groups;
},
getNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].name;
}
}
return null;
},
getShortNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].short_name;
}
}
return null;
},
getTeamsById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].team_ids;
}
}
return null;
}
};
return {
get: function(callback) {
if(!groups.length) {
$http.get('/api/groups')
.then(
function(response) {
groups = response.data;
callback(groupsObj);
}
);
} else {
callback(groupsObj);
}
}
};
});
The controller:
function GroupsOverviewCtrl($scope, groups) {
groups.get(function(groupsObj) {
$scope.groups = groupsObj.getAll();
});
}
GroupsOverviewCtrl.$inject = ['$scope', 'groups'];

How to create a dynamic file resource from angular service factory?

It is possible to have a dynamic file resource?
This is my factory
factory('fileResourcedc', function ($resource) {
var FileResourcedc = $resource(
'xml/file.json',{},
{
get:{method:'GET', isArray:false}
}
);
return FileResourcedc;
})
And I am calling it from here:
var deferred = $q.defer();
var successFn = function (result) {
if (angular.equals(result, [])) {
deferred.reject("Failed because empty : " + result.message);
}
else {
deferred.resolve(result);
}
};
var failFn = function (result) {
deferred.reject("Failed dataconfResponse");
};
fileResourcedc.get(successFn, failFn);
return deferred.promise;
Note that in my factory, the filename is hard coded:
'xml/file.json'
What I need is to create a filename parameter and pass it to factory service. Is it possible?
Thaks in advance
This was my solution:
factory('fileResourcedc', function ($resource) {
var FileResourcedc = $resource(
'xml/:myFile',
{},
{
get:{method:'GET', params:{myFile:""}, isArray:false}
}
);
FileResourcedc.prototype.getCatalogue = function (fileName, successCat, failCat) {
return FileResourcedc.get({myFile:fileName}, successCat, failCat);
};
return new FileResourcedc;
})
Call:
var deferred = $q.defer();
var successFn = function (result) {
if (angular.equals(result, {})) {
deferred.reject("No catalogue");
}
else {
deferred.resolve(result);
}
};
var failFn = function (result) {
deferred.reject("Failed catalogue");
};
fileResourcedc.getCatalogue("catalogues.json",successFn, failFn);
return deferred.promise;
Thanks!

Categories