Angularjs $resource get/post returning same result - javascript

I'm brand new to angular, so I'm probably doing things all wrong. My query is returning an array of objects like it should be. I then do a click event to test the post..it hits my web api just fine...but then it returns that same array from my get. I'm guessing this is cached? Why would my post show the results of my earlier get?
Edit - Sorry, I could have been more clear. When I run my saveTest method, a post fires and my array saves, however the 'result' variable of that save..is the array from my original get.
app.directive('referenceSection', function () {
return {
restrict: 'E',
templateUrl: '/app/loanapplication/views/reference-section.html',
controller: function ($scope, referenceService) {
$scope.json = angular.toJson($scope.referenceArray);
$scope.referenceArray = [];
referenceService.query().$promise.then(function (result) {
$scope.referenceArray = result;
}, function () {
alert("fail");
});
$scope.saveTest = function () {
referenceService.save(angular.toJson($scope.referenceArray)).$promise.then(function (result) {
var x = result;
}, function () {
alert("save fail");
});
}
}
};
});
Service
app.factory('referenceService', function ($resource) {
var requestUri = '/api/reference';
return $resource(requestUri)
});
Web api
public class ReferenceController : BaseController
{
public HttpResponseMessage Get()
{
List<WebReference> references = new List<WebReference>();
WebReference reference = new WebReference();
WebReference reference2 = new WebReference();
reference.Name = "Andrew";
reference.Relationship = "QuickSupport";
reference.Id = 1;
reference2.Name = "Josh";
reference2.Relationship = "Hansen";
reference2.Id = 2;
references.Add(reference);
references.Add(reference2);
if (references == null) throw new HttpResponseException(HttpStatusCode.NotFound);
return Request.CreateResponse<IEnumerable<WebReference>>(HttpStatusCode.OK, references);
}
public HttpResponseMessage Post([FromBody]WebReference[] references)
{
try
{
var msg = new HttpResponseMessage(HttpStatusCode.Created);
return msg;
}
catch (Exception e)
{
throw new HttpResponseException(HttpStatusCode.Conflict);
}
}
}
}

referenceService.query().$promise.then(function (result) {
$scope.referenceArray = result;
After this, you need to call $scope.$apply() to inform angular of your changes made to be bound. If I guessed your question correctly .
:-)

From where you are reading response? From x that is not available outside then function or it is mistake to not attach it to referenceArray
referenceService.save(angular.toJson($scope.referenceArray)).$promise
.then(function (result) {
var x = result;
}, function () {
alert("save fail");
});

Related

Set a function to await response when calling through another function

Using JavaScript and AngularJS, I have a controller function looking to set a bool based on the return of a service call, which awaits the return of an API call. How do I write the controller function to wait for the API response?
Controller...
var someBoolValue = false;
function firstCheck() {
// function checks other things
if (someCheck) {
// how do I set someBoolValue to await the response, this code did NOT work
SomeService.CheckforSomething(data, moreData).then(function (response) {
someBoolValue = response;
});
}
Service...
function CheckforSomething(data, moreData) {
var anImportantNumber = null;
var anotherNumber = 456;
// function does other things
anImportantNumber = 123;
if (someCondition) {
ApiService.GetMyData()
.then(function (data) {
anImportantNumber = data.ThisValue.WRT;
}
}
return (anImportantNumber != anotherNumber);
}
API Service...
function GetMyData() {
uri = 12345;
$http.get(uri)
.then(function (response) {
dererred.resolve(response.data)
}
return deferred.promise;
}

$watch a service when theres changes

I want to watch changes in my services like in my system logs when there's someone who login the getlogs function must trigger how to achieve this ???
dashboard.controller
function getLogs() {
return dataservice.getLogs().then(function (data) {
vm.logs = data;
return vm.logs;
});
}
dataservice.js
function getLogs() {
return $http.get('/api/timeLogs')
.then(success)
.catch(fail);
function success(response) {
return response.data;
}
function fail(e) {
return exception.catcher('XHR Failed for getPeople')(e);
}
}
I've tried this but its not working
$scope.$watch('dataservice.getLogs()', function () {
getLogs();
}, true);
This is a case for observable pattern where you subscribe for changes on your service
app.service('dataservice', function($http) {
var subscribers = [];
var addSubscriber = function(func){
subscribers.push(func);
}
var notifySubscribers = function(){
for(var i = 0; i< subscribers.length; i++){
subscribers[i](); //invoke the subscriber
}
};
var addLog = function(){
//let's say that the logs are added here
//then notify the subscribers that a new log has been added
notifySubscribers();
};
var getLogs = function() {
return $http.get('/api/timeLogs')
.then(success)
.catch(fail);
function success(response) {
return response.data;
}
function fail(e) {
return exception.catcher('XHR Failed for getPeople')(e);
}
};
return {
addSubscriber: addSubscriber,
addLog: addLog,
getLogs: getLogs
}
});
Then in your controller add a subscriber function to the service
dataservice.addSubscriber(function(){
console.log('new log added');
dataservice.getLogs();
});
NOTE: this can also be done with the RxJs library
if you want to check and get data's change from server, watching a service is not for that, use a polling service.
you check for every 1sec (for example) from a server:
example:
$interval(function() {
dataservice.getLogs().then(function(data) {
vm.logs = data;
});
}, 1000);
or much better:
getLogs = function () {
dataservice.getLogs().then(function(data){
vm.logs = data;
$timeout(getLogs, 1000)
});
}

Updating Json values with a promise

I want to populate some values in Json that are being calculated with angular-promises and these value should be updated after certain events.
I tried to call the factory which yields the values for example something like below and tried to call the functions GetWeeklyVal and GetDailyVal which are in charge of calculating the values :
this.salesList =
{"sales":[
{ "id":"A1", "dailyValue": GetDailyVal('A1'), "weeklyValue": GetWeeklyVal('A1')},
{ "id":"A2", "dailyValue": GetDailyVal('A2'), "weeklyValue": GetWeeklyVal('A2')}
]}
and in my controller I have:
$scope.sales= salesServices.salesList.sales;
but it didn't work. the values remain zero which is the default value in the application.
Why the values are not being updated and what would be a better solution?
update
This is the portion of the code I call the calculation functions: (I skip the portion to get the values based on passed id in here)
function GetDailyVal(id){
var dValue = 0;
salesService.getSales();
dValue = salesService.totalAmount;
return dValue;
}
this is the factory
.factory('salesService', ['$http', '$q'],
function salesInvoiceService($http, $q) {
var service = {
sales: [],
getSales: getSales,
totalAmount: 0
};
return service;
function getSales() {
var def = $q.defer();
var url = "http://fooAPI/salesinvoice/SalesInvoices"; //+ OrderDate filter
$http.get(url)
.success(function(data) {
service.sales = data.d.results;
setTotalAmount(service.sales);
def.resolve(service.sales);
})
.error(function(error){
def.reject("Failed to get sales");
})
.finally(function() {
return def.promise;
});
}
function setTotalAmount(sales){
var sum = 0;
sales.forEach(function (invoice){
sum += invoice.AmountDC;
});
service.totalAmount = sum;
}
})
I think there are some errors in your code.
I give some sample code here. I think this will help you.
This is a sample code in one of my application. Check it.
service.factory('Settings', ['$http','$q', function($http,$q) {
return {
AcademicYearDetails : function(Details) {
return $http.post('/api/academic-year-setting', Details)
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return $q.reject(response.data);
}
}, function(response) {
return $q.reject(response.data);
});
},
newUser : function(details) {
return $http.post('/api/new-user', details);
}
}
}]);
The reason why its not working is:
dailyValue: GetDailyVal('A1')
Here, GetDailyVal makes an async ajax call to an api. For handling async requests, you have to return a promise as follows in your GetDailyVal function as follows:
function GetDailyVal() {
salesService.getSales().then(function(data) { //promise
dValue = salesService.totalAmount;
return dValue;
})
}
Same thing need to be done for weeklyValue.

Can't execute 2 $http calls in angularjs at the same time

I am implementing long polling to know the state of some long running event on the server side. I create my own factory that will notify me when a server event triggers. Here is the factory.
.factory("$httpPolling", function ($http) {
function $httpPolling($httpService) {
var _responseListener, _finishListener;
var cancelCall = false;
var _pollId;
function waitForServerCall(id) {
console.log("executing waitForServerCall");
$httpService.get(href("~/polling/" + id))
.success(function (response) {
var cancelPolling = _responseListener(response);
if (cancelPolling || cancelCall) {
return;
}
else {
waitForServerCall(id);
}
});
};
function _sendData(httpMethod, url) {
var pollingId = guid();
_pollId = pollingId;
if (url.split("?").length == 2) {
url += "&pollid=" + pollingId;
}
else {
url += "?pollid=" + pollingId;
}
if (httpMethod == 0) {
$httpService.get(url).success(function (response) {
if (_finishListener) {
_finishListener(response);
}
cancelCall = true;
});
}
else {
$httpService.post(url).success(function (response) {
if (_finishListener) {
_finishListener(response);
}
cancelCall = true;
});
}
}
var $self = this;
this.get = function (url) {
_sendData(0,url);
return $self;
};
this.post = function (url) {
_sendData(1, url);
return $self;
};
this.listen = function (_listener) {
_responseListener = _listener;
waitForServerCall(_pollId);
return $self;
}
this.finish = function (_finish) {
_finishListener = _finish;
return $self;
}
}
return new $httpPolling($http);
});
Where the sintax of usage should be:
$httpPolling.get("url")
.listen(function(event){
// fires when server event happend
})
.finish(function(response){
// fires when the long running process finish
});
The problem is that _sendData method does not execute asynchronously because the waitForServerCall only executes the ajax call when the _sendData(long running process) method get the response from the server.
Why? Is this an angular behavior?
Angular $httpProvider has an option provided for async http calls, which is set to false as default value.
Try
app.config(function ($httpProvider) {
$httpProvider.useApplyAsync(true);
});

Angularjs Factory deferred's data disapearing

I'm trying to do a caching factory for http requests, so it doesn't make the server do a lot of work for the same request. But It seems my way of using deferred "swallows" the data, and I don't know why.
Console output for below:
data fetched:
Object {state: "OK", data: Object, errorMessage: null, exception: null}
success
undefined
ImportFactory:
factory("importFactory", function ($http, $q, loggingService) {
return{
fetchedData: [],
cacheTransport: function (transportsId, data) {
this.fetchedData.push({"transportsId": transportsId, "data": data});
},
getImport: function (transportsId) {
var factory = this;
var deferred = $q.defer();
var preFetchedTransport = this.findTransport(transportsId);
if (preFetchedTransport === null) {
console.log('fetching from backend');
return $http.post("/import/create/" + transportsId).then(function (data) {
console.log('data fetched:');
console.log(data);
factory.cacheTransport(transportsId, data);
deferred.resolve(data);
});
}
preFetchedTransport = deferred.promise;
return preFetchedTransport;
},
findTransport: function (transportsId) {
for (var i = 0; i < this.fetchedData.length; i++) {
var transportObj = this.fetchedData[i];
if (transportObj.transportsId === transportsId) {
return transportObj.data;
}
}
return null;
}
};
});
Controller
.controller('ImportController', function ($scope, $routeParams, importFactory){
$scope.transportId = $routeParams.id;
importFactory.getImport($scope.transportId).then(function (successData) {
console.log('success');
console.log(successData);
}, function (errorData) {
console.log('error');
console.log(errorData);
});
You basically need this: Demo here.
var cachedPromises = {};
return {
getStuff: function(id) {
if (!cachedPromises[id]) {
cachedPromises[id] = $http.post("/import/create/" + id).then(function(resp) {
return resp.data;
});
}
return cachedPromises[id];
}
};
Now, when you fetch that data, you can manipulate and it will be changed when you access it in the future.
myService.getStuff(whatever).then(function(data) {
data.foo = 'abc';
});
//elsewhere
myService.getStuff(whatever).then(function(data) {
console.log(data.foo); // 'abc'
});
Here's a demo that does this, as well as a view updating trick (bind the object to the view before the data comes in), and an idea of how you could change the data separately from the cache, in case you want to have the original data and the changing data. http://jsbin.com/notawo/2/edit
Remember to avoid that nasty promise anti-pattern. If you already have a promise, use that instead of creating another with $q. $http already returns a promise and that promise is sufficient for whatever you need if you use it properly.
just change the loop condition look like this and then test i think your function and defer is work fine but the loop does not sent the correct data
for(var i = 0; i < this.fetchedData.length; i++) {
if (this.fetchedData[i].transportsId === transportsId) {
return this.fetchedData[i].data;
}
}
return null;
}
The reason you are getting undefined is you are not returning anything from the $http.post().then() !
Also in your getImport() function you are returning an empty promise when the transport is already cached. You need to resolve it to your already cached transport object.
getImport: function (transportsId) {
var factory = this;
var deferred = $q.defer();
var preFetchedTransport = this.findTransport(transportsId);
if (preFetchedTransport === null) {
console.log('fetching from backend');
return $http.post("/import/create/" + transportsId).then(function (data) {
console.log('data fetched:');
console.log(data);
factory.cacheTransport(transportsId, data);
return data; //this was missing
});
}
// resolve it with transport object if cached
deferred.resolve(preFetchedTransport);
return deferred.promise;
},

Categories

Resources