refresh an array without refreshing the page in angularJS - javascript

I have an array that I want to affect to it data that I have get from my Factory,but when I try to access it I don't get the data recently added to it,this the array when I try to fill it whith data:
$scope.copyofOpList = [];
$scope.UpdateOperations = function() {
$scope.copyofOpList = gammeOfFactory.getListOperations();
}
this is my Factory from which I get the Data:
.factory(
'gammeOfFactory',
function($http, $q) {
var backObject = {
getListOperations: _getListOperations
}
return backObject;
//used to get list of operations from ws
function _getListOperations() {
var defer = $q.defer();
$http({
method: "GET",
url: "MyWebService/getAll"
}).then(function mySucces(response) {
defer.resolve(response.data);
}, function myError(response) {
deferred.reject('Erreur into url ' + response);
});
return defer.promise;
};
});
so please,how can I refresh the Data in this array without refreshing the web page
thanks for help

Related

Why is my datasource not returning all my data in Angular grid application>?

Let me first preface this by saying...I'm a noob and have been pouring over documentation already but I have not found a resolution.
I have built a custom report in PowerSchool SIS using AngularJS to form my grid and am using JSON data to fill it. The problem I am currently having is the grid is only populating 100 items even though there are close to 200 record items.
This is my JS:
//Begin Module - Loads AngularJS
define(['angular', 'components/shared/index'], function(angular) {
var attApp = angular.module('attApp', ['powerSchoolModule']);
// var yearid = window.location.search.split("=")[1];
//Begin Controller
attApp.controller('attCtrl', ['$scope', 'getData', '$attrs', function($scope, getData, $attrs) {
$scope.curSchoolId = $attrs.ngCurSchoolId;
$scope.curYearId = $attrs.ngCurYearId;
loadingDialog();
$scope.attList = [];
//Sets definition of the var dataSource to pull PowerQueries
var dataSource = {
method: "POST",
url: "/ws/schema/query/com.cortevo.reporting.attendance.absencebymonthschoolgrade",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
data: {yearid},
dataType: "json",
pages:"50",
};
console.log(dataSource);
//Sets definition of the var dataSource to pull from JSON files
console.log('loading dataSource');
//var dataSource= {method: "GET", url: "attendancedata.json"};
getData.getAttData(dataSource).then(function(retData) {
if (!retData.record) {
alert('There was no data returned');
closeLoading();
} else {
console.log(retData);
if (!!retData.record[retData.record.length]) {
// retData.record.pop();
}
var i = retData.record.length;
while (i--) {
retData.record[i].attendance_date = new Date(retData.record[i].attendance_date) // Changes the text of the attendance date to a JS data
}
//Sets scope of attList and attName
$scope.attList = retData.record;
$scope.attName = retData.name;
console.log($scope.attList);
closeLoading();
}
});
}]); //End Controller
//Begins factory and invokes PowerQueries if available, error message will trigger if no data returned
attApp.factory('getData', function($http) {
return {
getAttData: function(dataSource) {
return $http(dataSource).then(function successCallback(response) {
return response.data;
},
function errorCallback(response) {
alert('There was an error returning data');
});
}
}
}); //End Factory
}); //End Module
We have confirmed there is nothing wrong with my datasource. I'm stuck and could use a guiding word. Any advice would be appreciated.
Try to hit the same endpoint using PostMan, maybe the API is not working.
Also I'm not sure if this url is valid:
url: "/ws/schema/query/com.cortevo.reporting.attendance.absencebymonthschoolgrade"

Problem inizialise a global variable AngularJS by calling a REST service

I want to create a global variable (httpTimeout) initialize at the start, contains a Long value returned by a synchrone call Rest Service and used it in different service
(
function () {
'use strict';
angular
.module('module')
.factory('MyService', function (
$http,
$q
){
var service = {};
var httpTimeout = function() {
return $http({
method: 'GET', '.../rest/getHttpTimeOut'
}).then(function (response) {
return response.data;
}).catch(function (err) {
return 30000;
});
};
service.myService1= function (Model) {
return $http({
method: 'POST', '..../rest/callRestService1',
data: Model, timeout : httpTimeout
}).then(function (response) {
return response.data;
});
};
service.myService2= function (Model) {
return $http({
method: 'POST', '..../rest/callRestService2',
data: Model, timeout : httpTimeout
}).then(function (response) {
return response.data;
});
};});
My rest service
#RequestMapping(value = "/getHttpTimeOut", method = RequestMethod.GET)
#ResponseBody
public long getHttpTimeOutValue() {
return timeoutValue;
}
how i can retrieve this value globally (httpTimeout) for use in other services
Thank you for your help
if your question is how to do something on application start :
look at that
After your application start you can use another service to store the value.
Also if you want to apply this comportement for all request take a look to interceptor

Angular - How can i pass a parameter into a deferred promise?

Working on my first Angular app here so excuse me if question not clear.
I have a service which gets from my api using a group variable in the header.
var theReq = {
method: 'GET',
url: API + '/homeq',
headers: {
'group': 'mobile'
}
};
$http(theReq)
.then(function(data){
deferred.resolve(data);
})
self.getResults = function() {
return deferred.promise;
}
The issue I'm facing is with using the group variable that i specify rather than that preset one.
I can surely pass it into that function (i.e. self.getResults = function(groupToGet)) but how would it get from there to theReq that I process?
Any help appreciated.
Thanks.
You need to modify your function in following manner. $q is the service to create deferred objects. You need to inject it.
self.getResults = function(groupToSet) {
var deferred = $q.defer();
var theReq = {
method: 'GET',
url: API + '/homeq',
headers: {
'group': groupToSet
}
};
$http(theReq)
.then(function(data){
deferred.resolve(data);
})
return deferred.promise;
}
and you can use promise as
self.getResults("mobile").then(function(data) {
//success function here.
}).catch(function(error) {
//error function here
});

How to execute simultaneously an $http in angularjs

I have a module(app) which contains inside a service(globalService) with $http. This module now is included inside another module (invoicesApp) which has a service(invoicesService) too. Using the service of the second module I'm loading the service of the first service and returning back some information. The problem which I'm having is that the parameters of the first service are overridden from the second service and for that reason both $http are executing the same request. Here is my code
This is my first Service:
(function(angular){
var app = angular.module('app',[])
.config(function($locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
})
.service('globalService', function($http, $location,$q){
console.log("globalService");
this.getPaging = function()
{
var deferred = $q.defer();
var paging_parameters = $location.search();
paging_parameters.action = "client_pagination";
var req = {
url: ajaxpagingscript.ajaxurl,
method: "GET",
params: paging_parameters
}
$http(req).success(function(paging_data) {
console.log("globalService " + JSON.stringify(paging_data));
deferred.resolve(paging_data.paging);
}).error(function(data, status, headers)
{
$scope.error = "";
});
return deferred.promise;
}
});
})(window.angular);
Second Service:
(function(angular){
var invoicesApp = angular.module('invoicesApp',['ngRoute','app'])
.config(function($locationProvider,$routeProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
})
.controller('InvoicesController', ['$scope','transactionService',
function($scope,invoicesService) {
$scope.invoices = [];
console.log("testing");
var paging = invoicesService.getPaging();
var promise = invoicesService.getInvoicess();
promise.then(function(data)
{
console.log("invoices " +JSON.stringify(data));
angular.forEach(data.new_data, function(JSON_ARRAY) {
$scope.invoicearray.push(JSON_ARRAY);
});
});
}])
.service('invoicesService', function(globalService, $http,$location,$q){
this.getPaging = function() { return globalService.getPaging(); };
this.getInvoicess = function() {
var deferred = $q.defer();
var invoices_parameters = $location.search();
invoices_parameters.action = "collect_invoice_data";
var req = {
url: ajaxpagingscript.ajaxurl,
method: "GET",
params: invoices_parameters
};
$http(req).success(function(data) {
deferred.resolve(data);
}).error(function(data, status, headers)
{
$scope.error = "";
});
return deferred.promise;
};
});
})(window.angular);
The console.log for both services, returning back the same data. The page that loads this app, loads invoicesApp so the globalService is executed fine but the parameters that pass to $http are wrong. Can anyone help me?
You don't need to call the function, you need to pass the reference of the function if that is what you are trying to do in invoicesService.
this.getPaging = function() { return globalService.getPaging(); };
should be
this.getPaging = globalService.getPaging;

AngularJS: transform response in $resource using a custom service

I am trying to decorate the returned data from a angular $resource with data from a custom service.
My code is:
angular.module('yoApp')
.service('ServerStatus', ['$resource', 'ServerConfig', function($resource, ServerConfig) {
var mixinConfig = function(data, ServerConfig) {
for ( var i = 0; i < data.servers.length; i++) {
var cfg = ServerConfig.get({server: data.servers[i].name});
if (cfg) {
data.servers[i].cfg = cfg;
}
}
return data;
};
return $resource('/service/server/:server', {server: '#server'}, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(data, header) {
return mixinConfig(angular.fromJson(data), ServerConfig);
}
},
get: {
method: 'GET',
isArray: false,
transformResponse: function(data, header) {
var cfg = ServerConfig.get({server: 'localhost'});
return mixinConfig(angular.fromJson(data), ServerConfig);
}
}
});
}]);
It seems I am doing something wrong concerning dependency injection. The data returned from the ServerConfig.get() is marked as unresolved.
I got this working in a controller where I do the transformation with
ServerStatus.get(function(data) {$scope.mixinConfig(data);});
But I would rather do the decoration in the service. How can I make this work?
It is not possible to use the transformResponse to decorate the data with data from an asynchronous service.
I posted the solution to http://jsfiddle.net/maddin/7zgz6/.
Here is the pseudo-code explaining the solution:
angular.module('myApp').service('MyService', function($q, $resource) {
var getResult = function() {
var fullResult = $q.defer();
$resource('url').get().$promise.then(function(data) {
var partialPromises = [];
for (var i = 0; i < data.elements.length; i++) {
var ires = $q.defer();
partialPromisses.push(ires);
$resource('url2').get().$promise.then(function(data2) {
//do whatever you want with data
ires.resolve(data2);
});
$q.all(partialPromisses).then(function() {
fullResult.resolve(data);
});
return fullResult.promise; // or just fullResult
}
});
};
return {
getResult: getResult
};
});
Well, Its actually possible to decorate the data for a resource asynchronously but not with the transformResponse method. An interceptor should be used.
Here's a quick sample.
angular.module('app').factory('myResource', function ($resource, $http) {
return $resource('api/myresource', {}, {
get: {
method: 'GET',
interceptor: {
response: function (response) {
var originalData = response.data;
return $http({
method: 'GET',
url: 'api/otherresource'
})
.then(function (response) {
//modify the data of myResource with the data from the second request
originalData.otherResource = response.data;
return originalData;
});
}
}
});
You can use any service/resource instead of $http.
Update:
Due to the way angular's $resource interceptor is implemented the code above will only decorate the data returned by the $promise and in a way breaks some of the $resource concepts, this in particular.
var myObject = myResource.get(myId);
Only this will work.
var myObject;
myResource.get(myId).$promise.then(function (res) {
myObject = res;
});

Categories

Resources