Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm just trying resolving promises from a factory like this:
.config(['$routeProvider', '$locationProvider', '$httpProvider', 'SoundRTCProvider', function ($routeProvider, $locationProvider, $httpProvider, SoundRTCProvider) {
$routeProvider
.when('/',{
templateUrl:'views/home/index.html',
controller:'Home',
resolve: {
load: function (configFactory) {
return configFactory.loadAll();
}
}
});
});
then :
.factory('configFactory',['$rootScope', '$q', '$location', '$anchorScroll', '$routeParams', 'ngDialog', 'cacheService', 'sessionFactory', 'geoFactory', 'instrumentsFactory', 'genresFactory', 'langFactory', 'usersFactory', 'contactsFactory', function ($rootScope, $q, $location, $anchorScroll, $routeParams, ngDialog, cacheService, sessionFactory, geoFactory, instrumentsFactory, genresFactory, langFactory, usersFactory, contactsFactory) {
var initConfig = function () {
var deferred = $q.defer();
/*CONFIG PARAMS*/
$rootScope.config = {};
$rootScope.config.appWs = '';
$rootScope.config.appName = 'Dunno';
deferred.resolve('go');
return deferred.promise();
};
var initUserSession = function () {
var deferred = $q.defer();
/*----- INIT USER SESSION ---*/
$rootScope.session = {};
/*RELOAD SESSION if logged*/
if(sessionFactory.get('idUser')){
usersFactory.getMyProfile().then(function(results){
sessionFactory.initSession(results.data);
deferred.resolve();
});
}
return deferred.promise();
};
var initGravatar = function () {
var deferred = $q.defer();
/*------- INIT GRAVATARS ------*/
$rootScope.gravatar = {};
deferred.resolve();
return deferred.promise();
};
var initLang = function () {
var deferred = $q.defer();
/*------LANGUAGE---------*/
$rootScope.userLang = 'en_EN';
$rootScope.lang = {};//get key and value from here in views
//If user lang doesn't exists yet
if(cacheService.isExpired('appLang')) {
langFactory.getAll($rootScope.userLang)
.then(function (response) {
if(angular.isObject(response.data) && Object.keys(response.data).length > 0) {
cacheService.put('appLang',response.data,$rootScope.config.minChacheTime);
$rootScope.lang = cacheService.get('appLang');
} else {
$rootScope.lang = cacheService.get('appLang');
}
deferred.resolve();
});
} else {
deferred.resolve();
$rootScope.lang = cacheService.get('appLang');
}
return deferred.promise();
};
var initGenres = function () {
var deferred = $q.defer();
/*-------GENRES-------*/
if(cacheService.isExpired('appGenres')) {
genresFactory.getAll()
.then(function (response) {
if(angular.isObject(response.data) && Object.keys(response.data).length > 0) {
cacheService.put('appGenres',response.data,$rootScope.config.minChacheTime);
$rootScope.config.appGenres = cacheService.get('appGenres');
} else {
$rootScope.config.appGenres = cacheService.get('appGenres');
}
deferred.resolve();
});
} else {
deferred.resolve();
$rootScope.config.appGenres = cacheService.get('appGenres');
}
return deferred.promise();
};
var initInstruments = function () {
var deferred = $q.defer();
/*------INSTRUMMENTS------*/
if(cacheService.isExpired('appInstruments')) {
instrumentsFactory.getAll()
.then(function (response) {
if(angular.isObject(response.data) && Object.keys(response.data).length > 0) {
cacheService.put('appInstruments',response.data,$rootScope.config.minChacheTime);
$rootScope.config.appInstruments = cacheService.get('appInstruments');
} else {
$rootScope.config.appInstruments = cacheService.get('appInstruments');
}
deferred.resolve();
});
} else {
deferred.resolve();
$rootScope.config.appInstruments = cacheService.get('appInstruments');
}
return deferred.promise();
};
var initGeo = function () {
var deferred = $q.defer();
/*-------GEO----------*/
if(cacheService.isExpired('appGeo')) {
geoFactory.getAll()
.then(function (response) {
if(angular.isObject(response.data) && Object.keys(response.data).length > 0) {
cacheService.put('appGeo',response.data,$rootScope.config.minChacheTime);
$rootScope.config.appGeo = cacheService.get('appGeo');
} else {
$rootScope.config.appGeo = cacheService.get('appGeo');
}
deferred.resolve();
});
} else {
deferred.resolve();
$rootScope.config.appGeo = cacheService.get('appGeo');
}
return deferred.promise();
};
var initUserContacts = function () {
var deferred = $q.defer();
/*CONTACTS*/
$rootScope.contacts = {
approved: [],
pending: []
};
if(sessionFactory.get('idUser')){
contactsFactory.getMine().then(function (res) {
if(angular.isArray(res.data) && res.data.length > 0) {
for(var i in res.data) {
//set all my pending contacts
if(res.data[i].approved !== 1) {
$rootScope.contacts.pending.push(res.data[i].idContact);
} else {
//set all my contacts
$rootScope.contacts.approved.push(res.data[i].idContact);
}
}
}
deferred.resolve();
});
} else {
deferred.resolve();
}
return deferred.promise();
};
var initLayout = function () {
var deferred = $q.defer();
/*LAYOUT*/
$rootScope.layout = {
loading:true,
userMenu:false
};
deferred.resolve();
return deferred.promise();
};
var initScroll = function () {
var deferred = $q.defer();
//Make app scroll to top by default while navigating or use #anchor in url like http://sitess.com/someroute/?scrollTo=<:idelement:> to make it scroll to that element :id:
$location.hash($routeParams.scrollTo);
$anchorScroll();
deferred.resolve();
return deferred.promise();
};
var initDialog = function () {
var deferred = $q.defer();
//Close any dialog
ngDialog.close();
deferred.resolve();
return deferred.promise();
};
var loadAll = function () {
var deferred = $q.defer();
initConfig()
.then(function(){
return initUserSession();
}).then(function () {
return initLang();
}).then(function () {
return initGenres();
}).then(function () {
return initGeo();
}).then(function () {
return initInstruments();
}).then(function () {
return initUserContacts();
}).then(function () {
return initGravatar();
}).then(function () {
return initLayout();
}).then(function () {
return initScroll();
}).then(function () {
return initDialog();
}).then(function () {
$rootScope.$on('loading:end', function(){
$rootScope.layout.loading = false;
});
$rootScope.$on('loading:progressing', function (){
$rootScope.layout.loading = true;
});
$rootScope.$on('$locationChangeError', function () {
//hide loading gif
$rootScope.layout.loading = false;
//hide loading gif
$rootScope.layout.userMenu = false;
});
//all done with configs
deferred.resolve();
});
return deferred.promise();
};
return {
initConfig:initConfig,
initUserSession:initUserSession,
initLang:initLang,
initGenres:initGenres,
initGeo:initGeo,
initGravatar:initGravatar,
initInstruments:initInstruments,
initUserContacts:initUserContacts,
initLayout:initLayout,
initScroll:initScroll,
initDialog:initDialog,
loadAll:loadAll
};
}]);
What's up why do i get Error in console : TypeError: object is not a function
at initConfig (assets/js/factories.js:35:23)
that means the first return deferred.promise(); is generating the error, i can't understand whats wrong, any help appriciated thanks
You are trying to execute a normal object as a function (which is what the error means). It should be: return deferred.promise; instead of: return deferred.promise();.
Related
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;
});
}
I have many $http requests as following:
Scholarship.loadMaxAcademicYear().success(function (AcademicYearId) {
if (AcademicYearId) {
Scholarship.deleteAllCurrentData(data).success(function () {
Scholarship.copyDataToCurrentYear().success(function(){
Scholarship.getPromises(null, AcademicYearId).then(function () {
$scope.isSuccess = true;
$timeout(function () {
$scope.isSuccess = false;
$scope.isSubmit = false;
$scope.confirmModal.close();
}, 5000);
}, function(err){
importError();
});
}).error(function(){
importError();
})
}).error(function(){
importError();
});
}
}).error(function (err) {
importError();
});
I want to reduce the error callback to be only one at the end as following:
Scholarship.loadMaxAcademicYear().success(function (AcademicYearId) {
if (AcademicYearId) {
Scholarship.deleteAllCurrentData(data).success(function () {
Scholarship.copyDataToCurrentYear().success(function(){
Scholarship.getPromises(null, AcademicYearId).then(function () {
$scope.isSuccess = true;
$timeout(function () {
$scope.isSuccess = false;
$scope.isSubmit = false;
$scope.confirmModal.close();
}, 5000);
}
})
})
}
}).error(function (err) {
importError();
});
I'm thinking of using the async but Angular might have some way to handle this kind of problem. Would it be possible to do so in AngularJs?
You've still got a pyramid of doom even in your second example. The key here is to use the .then() method to allow promise chaining:
Scholarship.loadMaxAcademicYear().then(function(response) {
var academicYearId = response.data;
if (academicYearId) {
return Scholarship.deleteAllCurrentData(academicYearId)
.then(function() {
return Scholarship.copyDataToCurrentYear();
}).then(function() {
return Scholarship.getPromises(null, academicYearId);
}).then(function() {
$scope.isSuccess = true;
return $timeout(function() {
$scope.isSuccess = false;
$scope.isSubmit = false;
$scope.confirmModal.close();
}, 5000);
});
}
}).catch(function(err) {
importError();
});
We can also shorten this a bit by using .bind():
Scholarship.loadMaxAcademicYear().then(function(response) {
var academicYearId = response.data;
if (academicYearId) {
return Scholarship.deleteAllCurrentData(academicYearId)
.then(Scholarship.copyDataToCurrentYear.bind(Scholarship))
.then(Scholarship.getPromises.bind(Scholarship, null, academicYearId))
.then(function() {
$scope.isSuccess = true;
return $timeout(function() {
$scope.isSuccess = false;
$scope.isSubmit = false;
$scope.confirmModal.close();
}, 5000);
});
}
}).catch(importError);
I am trying to do a resolve with a promise due to an issue with a filters I am working on, but, my resolve isn't working yet.
I am doing this because in a question I did before some one asked me to do a resolve which is the must logic solution I got from other people.
This what the console returns:
localhost:1337/lines/sports/undefined:1
GET http://localhost:1337/lines/sports/undefined 400 (Bad Request)
Take a look at my code:
app.js
.state('app.sports', {
url:'/sports',
views:{
menuContent:{
templateUrl:'templates/sportsList.html',
controller:'SportsController',
resolve: {
Sports: function(SportsFactory, AuthFactory, $q) {
var defer = $q.defer();
console.log(AuthFactory);
AuthFactory.getCustomer().then(function() {
SportsFactory.getSports().then(function(sports) {
defer.resolve(sports);
});
});
return defer.promise;
}
}
controller.js
.controller('SportsController', function($scope, $state,
AuthFactory, SportsFactory, Sports) {
$scope.query = '';
$scope.sports = Sports;
$scope.sports = [];
$scope.customer = {};
});
AuthFactory.getCustomer().then(function(customer) {
$scope.customer = customer;
SportsFactory.getSportsWithLeagues(customer).then(function(sports) {
if (sports.length) {
$scope.sports = sports;
}else {
AuthFactory.logout();
}
}, function(err) {
console.log(err);
});
}, function(err) {
console.log(err);
});
service.js
.factory('SportsFactory', function($http, $q, AuthFactory,
LocalForageFactory, LeaguesFactory, CONSTANT_VARS) {
return {
getSports: function(agent) {
var defer = $q.defer();
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS)
.then(function(sports) {
if (!_.isNull(sports)) {
defer.resolve(_.values(sports));
}else {
$http.get(CONSTANT_VARS.BACKEND_URL + '/lines/sports/' + agent)
.success(function(sports) {
//forcing array instead of object
sports = _.values(sports);
sports = _.sortBy(sports, function(sport) {
return sport.priority;
});
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS, sports);
defer.resolve(sports);
})
.error(function(err) {
defer.reject(err);
});
}
});
return defer.promise;
},
getSportsWithLeagues: function(customer) {
var _this = this,
defer = $q.defer(),
rejection = function(err) {
defer.reject(err);
},
sportsLength;
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES)
.then(function(sportLeagues) {
if (!_.isNull(sportLeagues)) {
//forcing array instead of object
sportLeagues = _.values(sportLeagues);
defer.resolve(sportLeagues);
}else {
_this.getSports(customer.agent).then(function(sports) {
sportsLength = sports.length;
LeaguesFactory.getLeagues({
sportIds: _.pluck(sports, 'id'),
lineProfile: customer.lineProfile,
betLimit: customer.betLimit
}).then(function(leagues) {
_.each(sports, function(sport) {
sport.leagues = _.filter(leagues, function(league) {
return sport.id === league.sport.id;
});
});
//forcing array instead of object
sports = _.values(sports);
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES, sports);
defer.resolve(sports);
}, rejection);
}, rejection);
}
}, rejection);
return defer.promise;
}
};
});
and this is the authFactory:
.factory('AuthFactory', function($q, $http, $state,
LocalForageFactory, CONSTANT_VARS) {
return {
/**
* This function logs the customer, if the customer exists,
* Customer data is saved in order to perform actions,
* if not, an error message is returned.
* #param credentials a json with this format {username: 'jhon', password:'D03'}
* #returns {Animation.promise|promise}
*/
login: function(credentials) {
var defer = $q.defer(),
_this = this;
$http.post(CONSTANT_VARS.BACKEND_URL + '/auth/login',
credentials
).success(function(data) {
if (data.error) {
defer.reject(data);
}
_this.setCustomer(data).then(function(customer) {
defer.resolve(customer);
}, function(err) {
defer.reject(err);
});
}).error(function(data, status) {
if (status === 0) {
data = new Error('Backend is down');
data.raw = {};
}
defer.reject(data);
});
return defer.promise;
},
setCustomer: function(customer) {
var defer = $q.defer();
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_CUSTOMER, customer).then(function(customer) {
/*Removing LocalForage Items*/
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_LEAGUES);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS);
defer.resolve(customer);
}, function(err) {
$state.go('app.login');
defer.reject(err);
});
return defer.promise;
},
updateCustomer: function(customer) {
var defer = $q.defer();
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_CUSTOMER, customer).then(function(customer) {
defer.resolve(customer);
}, function(err) {
$state.go('app.login');
defer.reject(err);
});
return defer.promise;
},
getCustomer: function() {
var defer = $q.defer();
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_CUSTOMER).then(function(customer) {
if (customer) {
defer.resolve(customer);
}else {
defer.reject(new Error());
}
defer.reject(customer);
}, function(err) {
defer.reject(err);
});
return defer.promise;
},
logout: function() {
var defer = $q.defer();
this.getCustomer().then(function(credentials) {
$http.post(CONSTANT_VARS.BACKEND_URL + '/auth/logout',
credentials
).success(function(data) {
if (data.error) {
defer.reject(data);
}
/*Removing LocalForage Items*/
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_LEAGUES);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_CUSTOMER);
defer.resolve(data);
}).error(function(data) {
defer.reject(data);
});
}, function(err) {
$state.go('app.login');
defer.reject(err);
});
return defer.promise;
},
updateToken: function(token) {
var _this = this,
defer = $q.defer();
this.getCustomer().then(function(customer) {
customer.token = token;
_this.updateCustomer(customer).then(function(savedCustomer) {
defer.resolve(savedCustomer);
}, function(err) {
defer.reject(err);
});
}, function(err) {
defer.reject(err);
});
return defer.promise;
},
customerInfo: function() {
var defer = $q.defer();
this.getCustomer().then(function(customer) {
$http.post(CONSTANT_VARS.BACKEND_URL + '/auth/info', customer)
.success(function(data) {
defer.resolve(data);
})
.error(function(err) {
defer.reject(err);
});
}, function(err) {
defer.reject(err);
});
return defer.promise;
}
};
});
In app.js your doing SportsFactory.getSports() , but getSports expects 'agent' argument. Since you are not supllying it with 'agent' this: '/lines/sports/' + agent equals this: lines/sports/undefined, which is why you are getting 400 (bad request). There might be other things wrong with this code, but this is the reason for the error message.
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;
}]);
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!