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!
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 am trying to make sync calls using a factory pattern.
$scope.doLogin = function (username, password, rememberme) {
appKeyService.makeCall().then(function (data) {
// data = JSON.stringify(data);
debugAlert("login controller app key service"+data);
var appkeyvalue = data.d.appkey;
sessionConfigurationService.setBasicToken(appkeyvalue);
loginService.makeCall(username, password, rememberme).then(function (accessTokenData) {
if (accessTokenData.access_token !== "")
{
sessionConfigurationService.setAccessTokenData(accessTokenData.access_token);
userPreferencesService.makeCall().then(function (userPreferencesData) {
if (userPreferencesData.d.userId !== "")
{
sessionConfigurationService.setUserPreferences(userPreferencesData.d);
// $window.location.href = '/base.html';
}
});
}
});
});
};
My appKeyService factory is
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function () {
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});
My authenticated service factory is
app.factory('authenticatedServiceFactory', function ($http, $q, sessionConfigurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function (methodType, URL, data, authType) {
var headerValue = "";
if (authType === "Basic") {
headerValue = sessionConfigurationService.getBasicToken();
} else if (authType === "Bearer") {
headerValue = sessionConfigurationService.getBearerToken();
}
var config = {headers: {
'Authorization': headerValue,
'Accept': 'application/json;odata=verbose',
},
withCredentials: true,
async: false
};
if (methodType === "GET") {
$http.get(URL, data, config)
.then(function (getData) {
debugAlert("GET method response" + JSON.stringify(getData));
deffered.resolve(getData.data);
}, function (error) {
debugAlert("GET method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "POST") {
$http.post(URL, data, config)
.then(function (putData) {
debugAlert("POST method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("POST method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "DELETE") {
$http.delete(URL, data, config)
.then(function (deleteData) {
debugAlert("DELETE method response" + JSON.stringify(deleteData));
deffered.resolve(deleteData.data);
}, function (error) {
debugAlert("DELETE method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "PUT") {
$http.put(URL, config)
.then(function (putData) {
debugAlert("PUT method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("PUT method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
return deffered.promise;
};
return service;
});
But I don't see the service calls are made in sync. So the "then" part in the controller is not executing after we receive the response. Its executing one after the other. How can I make that happen.
#Frane Poljak
Thank you for your comment. I just brought
var deffered = $q.defer();
inside the makeCall method and its working as I wanted now. Thank you!
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var service = {};
service.makeCall = function () {
var deffered = $q.defer();
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});
I want to get from my controller the result of an $http request.
Here is my service :
.service('postService', function($http, apiUrl) {
return {
post: function(uri, params) {
$http.post(apiUrl + uri, params).then(function(items) {
return items.data;
});
}
};
})
And here what I've done in my controller :
var getData = postService.post('my_service_url', {id: 'test'});
getData.then(function(result) {
$scope.data = result;
console.log(data);
});
But I catch the error :
getData is undefined
What is the way to achieve this ?
You need to return the $http.post
return {
post: function(uri, params) {
return $http.post(apiUrl + uri, params);
}
};
Then you can hook up your then:
var getData = postService.post('my_service_url', {id: 'test'});
getData.then(function(result) {
$scope.data = result;
console.log(data);
});
Try it with the $q module of angularjs:
https://docs.angularjs.org/api/ng/service/$q
Your service code could look like this:
.service('postService', function($http, $q, apiUrl) {
return {
post: function(uri, params) {
var deferred = $q.defer();
$http.post(apiUrl + uri, params).then(function(items) {
deferred.resolve(items.data);
}, function() {
// error case
deferred.reject();
});
return deferred.promise;
}
};
})
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;
}]);
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();.