AngularJS and Ionic click to repeat a failed http request - angularjs

I'm making an app using AngularJS and Ionic.
When my app sends a request to the server using $http and fails, I want a view to load to show the user a button which, when clicked, repeats the $http request that was just attempted.
Currently if the request fails, it will load an error view, but I want that error view to have a button which performs a repeated task when clicked. This will be the same error controller for all server errors, so needs to be adaptable and have a way to pass in or repeat all functions easily in one place.
function getData(){
$http({
url: remoteUrl+'/dat/get_data_app',
method: 'POST',
data: {}
}).then(function(response) {
}, function(response) {
//the getData is trying to pass in the current function so it can be repeated in the error controller
$localstorage.setObject('httpObj', getData());
$state.go('app.error');
});
}
Below is the error controller currently:
.controller('ErrorCtrl', function($scope, $localstorage, $recipes) {
var httpObj = $localstorage.getObject('httpObj');
//this needs to run as a funtion (only when button is clicked but I can sort that out, just need a way of passing the function here)
httpObj;
})
The error controller runs when the user lands on the error page. In order to make the controller short and not need much changing later, I want the function passed here to run on click of a button which I'll place here.
Adding the button isn't the problem, but I just want to know if there's an easy way to pass the function.
This whole way of doing it may be wrong but any thoughts will be appreciated :)
Thanks

Related

Pass service result to other controller

I am calling getLanguageSpecificData(LangCode) service from home controller and saving the data into localStorage. On Home page there are Language links, if user click on English then it will redirect to a second template. But the problem is that still home controller getLanguageSpecificData(LangCode) service is not completed its execution.So in second Controller when I am trying to get result from localStorage it is incorrect(not updated).
So can you please tell which is better approach in this situation ?
HomeController code :
app.controller('homeController',function($scope,$localStorage,$appService){
$scope.loadlanguagefile = function(langcode){
$troubleshootingService.getLanguageSpecificData(LangCode).then(function(responce){
$localStorage.data = responce.data;
});
}
});
'loadlanguagefile' function is called when user click on Enlgish link and app is redirect to second template. here is secondController code :
app.controller('secondController',function($scope,$localStorage){
$scope.data = $localStorage.data;
});
As per my suggestion, you should use callback function to do your need full, when the function is called make the English click disable , and if your result is successful the make that enable. It will be something like this:
getLanguageSpecificData(LangCode,callback:(dataToReturn:any)=>void):any{
//logic here to get data to return
callback(dataToReturn);
}
For calling this method -
1- before calling the method make English click disable.
2- then call the method-
getLanguageSpecificData(imputLangCode,(result)=>{
//logic for data modification
//logic to enable English click
});
3- Enable the English click inside the call of the method.

AngularJs $http get not working 1st time but does on subsequent invocations

All:
I have an Iframe tag on a simple HTML page and inside this Iframe tag is a HTML form - lets call it a widget. Its a form where the user can enter search criteria and click on a button to obtain the search results. I have decided to use Angularjs to make the necessary DB calls to a REST service that returns the search results back to the widget for display.
In testing this I enter a value in a textbox on the widget, that value being a value that I know exists in a particular table I'm testing against.
Here is my $http get call:
$http
.get('http://localhost/XXXXService/folder/getfolders/' +
$scope.formData.srchterm **==>** mapped to search textbox
).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
//$scope.formData = response;
//$scope.nrdFolderDataArray = response;
console.log('Success retrieving data.');
console.log(response.length);
console.log('response:');
console.log(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('Error occurred retrieving data.');
console.log(response.status);
console.log('returned data count:');
console.log(response.size);
console.log('response:');
console.log(response);
});
This call is inside a function called "submitForm" that is mapped to the widget with a "ng-submit="submitForm()" attribute on the submit button. And yes there are several log statements so I can try and figure out what is going on here. And what is happening is this: after entering a value in the textbox, THE FIRST TIME the search button is clicked the .get command does not work. I does not make the call to the REST service. I know this because I wrote the REST service and made sure I put in plenty of log statements while doing so and there are no log statements in the log file from the REST service. Instead the errorCallback block runs and I see all those log statements in the console. The "response" (object?) after THE FIRST call looks like this:
Object {data: null, status: 0, config: Object, statusText: ""} Method = GET Status = (canceled) type xhr
Further, in FF there is no response data to view in the Net tab of Firebug upon THE FIRST call, but there is response data to view in all subsequent calls.
So, interestingly enough each subsequent invocation of that $http.get call works! I see log statements in the log file from the REST service method and the successCallback block runs and I can see my data via those console.log messages.
Also, if I were to change the search value in the text box, which would then be THE FIRST TIME we would be searching for data for that new key, once again, the call does not work, but does work on subsequent clicks on the "search" button for that new key value.
I really am not sure if I have a CORS issue here since, other than THE FIRST calls each subsequent $http.get call works like a champ. Its just that very first call or first call after the search key has changed that the $http.get does not want to work.
I have tried setting headers in the .get call and I have tried using
#CrossOrigin(origins = "http://localhost/7001") as per
https://spring.io/guides/gs/rest-service-cors/ but I continue to have this issue on the first time invoking this .get call.
I've been dealing with this issue for way too many hours now and would sure appreciate some input as to why this is happening.
I'm sorry for being verbose here. I wanted to explain my issue thoroughly.
Please help.
Thank you
-g

ionic/angular refresh like count with interval?

HI I'm building out a basic social media site with ionic and am tracking the like counts for each post. On page load I successfully show the like count that is in the db for each record.
$scope.getNewData = function () {
$scope.page = 1;
// get generic feed
FeedService.getFeed(1)
.then(function (data) {
//We will update this value in every request because new posts can be created
// console.log(data.totalPages)
$scope.totalPages = data.totalPages;
$scope.cards = data.posts;
$scope.$broadcast('scroll.infiniteScrollComplete');
return "loaded new data";
})
.then(function (data) {
//$rootScope.$broadcast('newDataLoaded');
})
$scope.$broadcast('scroll.refreshComplete');
};
Issue is after the page loads and another user likes the record I want the like count to automatically update for all users. I started playing around with $interval which works but the whole $scope changes , almost looks like a page refresh. How can I only update the $scope.cards.Post_Likes_Count without having to refresh the entire $scope.cards?
Here is my markup:
<div class="actions-brief">
{{card.Post_Likes_Count}} Likes
<a ng-controller="CommentsCtrl" ng-click="showComments(card)" class="subdued">{{card.comments}} Comments</a>
<!--{{card.shares}} Shares-->
</div>
Ideally I would just want to refresh the $scope.cards.Post_Likes_Count. Not sure how to keep everything in sync if I don't use $scope.cards. I show 10 posts per page but as the user scrolls I grab 10 more records.
Any suggestions or tips would be greatly appreciated.
The whole $scope should not change ... According to best practices, you should make the $http call in factory or service. Lets say you made an http call to your server to update the like done by your one user... You should call activate() function..
Activate function should be a user defined function which makes a request to the server while loading the page to get all the data from database and reload the $scope.yourData variable with latest data.
Moreover you should call the same activate() function from your controller using $interval. This would make your code more structured and proper.
And moreover you should push data in your $scope.YOURDATA variable in your activate() function rather than assigning it each time...

Why $http in ng-init is not getting called everytime the view is loaded - AngularJS

I have modified my question as per my observation.$http request on server side is not happening whenever the view is called second or third or so on times although initWishList (ng-init) is getting called. The scenario is as below:
I have a My Account tab in the nav-bar, which opens a view having options like MyWishlist, My Address etc. When My wishlist is clicked for the first time, $http request happens, but when I again click on My Account (this time I don't see any call on server side when the .html view is loaded) , and then if I click My Wishlist , the controller is called but $http isn't called (this time I again dont see any call on server side from $http) but I can see the alert Init Called
Why so?
$scope.initWishList = function(){
alert('Init called')
$http.get("/get_wish_list/")
.success(function (response) {
$scope.refreshWishList(JSON.parse(response["products_json"]));
})
.error(function(){
console.log('Error');
});
};
Hope I have explained the scenario properly.
Controllers gets intialized only once when angular parses ng-controller directive. Since controller is initialized once, ng-init will also run once.
For your satisfaction, add a break point in the your controller on the first line, see when you hit that break point. Are you hitting that break point, every time you click the tab ? If not, ng-init will not be called every time

AngularJS $http.Post -> open the urllink + $http.get getting it

im still new with Angular and am trying to grasp the concept.
Currently I cant post code, but this is hopefully not a problem.
I have used https://docs.angularjs.org/api/ng/service/$http ... especially $http.post in order to Post some data I clicked in the current window
The following Code didnt work due to the error "$http function is not defined", even though $http was already declared... in the correct order I might add (I found other ppl who had issues with that due to the fact that they switched the parameters $scope, $http)
Thats my first Question is there a simple reason? I can add code tomorrow if necessary.
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Second Question: Well, but $http.post(..) with parameter url to the second site worked fine.. and in order to use the data i most likely need to use $http.get() at the second site... which I understand.
But how do I need to configure the $http.post that I actually open the url in my browser?
Well I hope you can help me ... sry that I currently can't give you my codeexamples, but I hope it's enough :)

Resources