I have a service getting items by $http. In the controller I share this data with the view. It works, but when I delete or add new items by $http, I cannot get my list to stay up to date.
I created a refresh() function, that I call every time I add or delete an item, but the refresh applies only from time to time. And not on every action though the function is always duly called and executed.
How should I proceed to get my items refreshed on every action?
Function:
refresh = function() {
itemsService.getItems().then(function(d) {
$scope.items= d;
});
}
Service:
app.factory('itemsService', function($http) {
var itemsService = {
getItems: function() {
return $http.get('items.json')
.then(
function (response) {
return response.data;
}
);
}
};
return itemsService;
});
I have also read about $watch() and tried to make it work in this case, but it does not seem to make any difference:
$scope.$watch('itemsService.getItems()', function(d) {
$scope.items = d;
}, true);
This might be what you are looking for
Angular JS - listen or bind $http request
You can just call your function when the request ends.
You can use an interceptor to do this
var httpinterceptor = function ($q, $location) {
return {
request: function (config) {
//show your loading message
console.log(config);
return config;
},
response: function (result) {
//hide your loading message
console.log('Repos:', result);
return result;
},
responseError: function (rejection) {
//hide your loading message
console.log('Failed with', rejection);
return $q.reject(rejection);
}
}
};
app.config(function ($httpProvider) {
$httpProvider.interceptors.push(httpinterceptor);
});
Related
I have this array I am getting through the following method:
var url= *url defined here*;
$scope.ViewProfile = function () {
$http.get(url)
.success(function (response) {
$scope.ProfileList = response;
$scope.FavNumbers = $scope.ProfileList[0].FavNumbers;
})
.error(function () {
});
}
I am required to edit the Fav Numbers list on the UI. and post it back to another url through http post url method. What I am stuck is with the concept of asynchronous calls, due to which I am unable to retrieve the favorite numbers list to be available for editing. Please help!
I have tried a method of using promises as follows:
app.factory('myService', function($http) {
var myService = {
async: function(url) {
var promise = $http.get(url).then(function (response) {
console.log(response);
return response.data;
});
// Return the promise to the controller
return promise;
}
};
return myService;
});
In my controller I am doing:
angular.module('JuryApp').controller('mycontroller', ['myService', function (myService) {
myService.async(url).then(function(d) {
$scope.data = d;
});
app.controller('MainCtrl', function( myService,$scope) {
// Call the async method and then do stuff with what is returned inside our own then function
myService.async().then(function(d) {
$scope.data = d;
});
});
But I keep getting the error 'd is not defined'. It keeps giving an error of some sort, where the debugger goes into an infinite loop or something.
You are overcomplicating it, I think. Async calls are actually pretty simple:
You're service:
app.factory("myService", ["$http", function($http) {
var MyService = {
getData: function(url) {
return $http.get(url); //$http returns a promise by default
}
};
return MyService;
})];
Your controller:
angular.module('JuryApp').controller('mycontroller', ['myService', function (myService) {
$scope.FavNumbers = [];
var url = "http://my.api.com/";
myService.getData(url).then(function(response) {
$scope.FavNumbers = response.data[0].FavNumbers;
});
}]);
That's all that you need to do.
I have a problem with angular spinner here, i have a update button inthat i'm using spin and loading needs to be stopped after saving the data in to database without using any timeout function i need stop that loading
function assignLectureToSubject(subject) {
subject.$update();
}
above code is the function for update button
Use a flag. lets call it isUpdating
$scope.isUpdating = false;
function update(){
$scope.isUpdating = true;
$http({
method: 'POST',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.isUpdating = false;
}, function errorCallback(response) {
$scope.isUpdating = false;
});
}
And in the HTML,
<your-spinner ng-show='isUpdating'>
Initially, spinner is hidden. When update is called, the spinner starts showing on the page. And when the event completes, the callback sets the flag to false, thereby hiding it again.
You can implement a genric solution, You can use interceptors, Here is an example. Perform your operation for ShowWaitIndicator and HideWaitIndicator functions
app.factory('waitingInterceptor', ['$q', '$rootScope',
function ($q, $rootScope) {
return {
request: function (config) {
ShowWaitIndicator();
return config || $q.when(config);
},
requestError: function(request){
HideWaitIndicator();
return $q.reject(request);
},
response: function (response) {
HideWaitIndicator();
return response || $q.when(response);
},
responseError: function (response) {
HideWaitIndicator();
return $q.reject(response);
}
};
}]);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('waitingInterceptor');
}]);
As title, I want to catch Http response that sent by the browser.
Let say a redirect to "http://domain/api/something", actually, a GET request to "http://domain/api/something" which return a JSON data. How can I get that data on first load using AngularJs?
You should modify your code as below
app.service('feedbackService', function ($http) {
this.getFeedbackPaged = function () {
return $http.get('http://domain/api/something');
};
});
app.controller('feedbackController', function ($scope, feedbackService, $filter) {
// Constructor for this controller
init();
function init() {
feedbackService.getFeedbackPaged().then(function(data){
$scope.feedbackItems=data;
});
}
});
Use $http service as follows.
$http.get(
'http://domain/api/something'
).then(function successCallback(response) {
$scope.data = JSON.parse(response.data);
}, function errorCallback(response) {
// error handler
});
reference: https://docs.angularjs.org/api/ng/service/$http
I'm trying to work out why the response of this service isn't saving to $scope.counter. I've added a function to my service fetchCustomers(p) which takes some parameters and returns a number, which I'd like to save to $scope.counter.
service
angular.module('app')
.factory('MyService', MyService)
function MyService($http) {
var url = 'URL'';
return {
fetchTotal: function(p) {
return $http.get(url, { params: p })
.then(function(response) {
return response.data.meta.total;
}, function(error) {
console.log("error occured");
})
}
}
}
controller
$scope.counter = MyService.fetchTotal(params).then(function(response) {
console.log(response);
return response;
});
For some reason though, this isn't working. It's console logging the value, but not saving it to $scope.counter. Any ideas?
If I understand your question correctly, you're setting $scope.counter to a promise, not the response.
MyService.fetchTotal(params).then(function(response) {
// Anything dealing with data from the server
// must be put inside this callback
$scope.counter = response;
console.log($scope.counter); // Data from server
});
// Don't do this
console.log($scope.counter); // Undefined
I have multiple controllers on a page that use the same service, for the sake of example we will call the service USER.
The first time the USER.getUser() is called it does an $http request to GET data on the user. After the call is completed it stores the data in USER.data. If another call is made to USER.getUser() it checks if there is data in USER.data and if there is data it returns that instead of making the call.
My problem is that the calls to USER.getUser() happen so quickly that USER.data does not have any data so it fires the $http call again.
Here is what I have for the user factory right now:
.factory("user", function($http, $q){
return {
getUser: function(){
var that = this;
var deferred = $q.defer();
if(that.data){
deferred.resolve(that.data);
} else {
$http.get("/my/url")
.success(function(res){
that.data = res;
deferred.resolve(that.data);
});
}
return deferred.promise;
}
}
});
I hope my question makes sense. Any help would be much appreciated.
Does this work for you?
.factory("user", function($http, $q) {
var userPromise;
return {
getUser: function () {
if (userPromise) {
return userPromise;
}
userPromise = $http
.get("/my/url")
.then(function(res) {
return res.data;
});
return userPromise;
}
}
})
$http already returns the promise for you, even more, in 2 useful types: success & error. So basically, the option that #kfis offered does NOT catch errors and not flexible.
You could write something simple:
.factory('user', function($http) {
return {
getUser: function() {
$http.get('/my/url/')
.success(function(data) {
return data;
})
.error(function(err) {
// error handler
})
}
}
})