AngularJS Form/HTTP/CORS - javascript

I have an Angular form connected to a REST API to insert a new row to a MySQL database. My REST API is working, but I am getting a CORS blocked notice in my web console. How can I get it to successfully send to the REST PI? Below is my controller code code:
countryApp.controller('AddLocation', function ($scope, $http) {
$scope.orglocation = {};
//
$scope.submit = function() {
var dataObj = {
location_title : $scope.location.location_title,
location_latitude : $scope.location.location_latitude,
location_longitude : $scope.location.location_longitude
}
//convert data to JSON string
var loc = JSON.stringify(dataObj);
$http.post('http://localhost/slimtest2/add_location', loc).
success(function(data, status, headers, config) {
alert("good");
}).
error(function(data, status, headers, config) {
alert("bye");
});
}
$scope.reset = function() {
$scope.location = angular.copy($scope.orglocation);
}
});

Generally when you hit a CORS problem it is a sign that your server is not configured correctly. I highly suggest looking at the MDN article on HTTP access control. The two headers that are most important to have in this case are:
access-control-allow-origin
access-control-allow-methods
Make sure the first is set to the domain and port you use to access your Angular app and that the second is set to the methods you use (in this case, at least POST).

Related

Error in returning java object to javascript

I am returning a java object to client(javascript) page, i.e. converting java object to JSON object but am facing no converter found for return value error.
I have added all spring jars and jackson-all-xxx.jar.
The below is the method that gets called from a html page using $http.get('url').
#RequestMapping(value="/springAngularJS",method=RequestMethod.GET)
public #ResponseBody Person getPerson() {
System.out.println("111111111");
Person person = new Person();
person.setFirstName("Java");
person.setLastName("Honk");
return person;
}
My html page: (posting only JS part)
var app = angular.module('myApp', []);
function MyController($scope, $http){
$scope.getPersonDataFromServer = function() {
$http.get("springAngularJS").
success(function(data, status, headers, config) {
$scope.person = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
};
Any help to resolve this would be appreciated..
I am a beginner..:)
Your problem is with project dependency and not code , as the above code is correct .
Again I suggest on you to start with Spring-boot it will allow you to concentrate on the code only working example

How do I test a string's values in Jasmine?

I have a string that is used to display text. It is initially set to null, then is updated throughout a function with status updates. I want to make sure the string is set to the correct status updates throughout the function's lifetime.
Jasmine's spies seem focused on testing functions and their interactions. I specifically want to test a string's history. Assuming the following code:
(function() {
$this.loggingIn = false;
$this.submit = function () {
$this.loggingIn = "Requesting access...";
$this.errorMessage = "";
var aThing = {};
var aSecondaryThing = {};
$http.post(aThing)
.success(function (data, status, headers, config) {
$this.loggingIn = "Validating credentials...";
$http.post(aSecondaryThing)
.success(function (data, status, headers, config) {
$this.loggingIn = "Done!";
})
.error(function (data, status, headers, config) {
$this.errorMessage = data.error_description || "Invalid username or password.";
$this.loggingIn = false;
});
})
.error(function (data, status, headers, config) {
$this.errorMessage = data.error_description || "Invalid username or password.";
$this.loggingIn = false;
});
return false;
};
})();
This function is abridged from our original Angular code. Nothing's missing aside from the wiring to make the controller work and the post actions.
Is there a way to test that loggingIn is set to "Validating credentials..." and then "Done!" without writing a setter function to handle it?
Ultimately we went with a setter function to handle the string management and testing. Although testing what the string actually says probably isn't needed, at the time it was required enough to need verification. That way we can verify if the function was being called, and then later verify the function changes the string correctly, which is proper testing in any case.

When I “Pull to refresh”, How I clean the Cache? With Ionic Framework and AngularJS

I have a problem, I'm using a JSON coming from an external server, but when I do "Pull to refresh" or when I open the application, displays the same information I downloaded the first time the application is opened. It may be that the JSON is being stored in the cache and therefore not update? For if when I go to on-refresh = "doRefresh ()" and called another JSON, (the first time I do), update, but re-enter the application I load the information from the first JSON and if I want update, showing me the information I also downloaded the first time. This will fix manually deleting the application data, but it is not the best way ...
This is my services.js
angular.module('starter.services', ['ngResource'])
.factory('NotasService', ['$http',
function ($http) {
var items_nota = [];
var items_nota_array;
return {
all: function () {
return $http.get('http://192.168.1.0:8100/wp-json/posts?filter[post_status]=publish&filter[posts_per_page]=30')
.success(function(data, status, headers, config){
console.log("**** SUCCESS ****");
console.log(status);
})
.error(function(data, status, headers, config){
console.log("**** ERROR ****");
console.log(status);
})
.then(function(response){
console.log("**** THEN ****");
items_nota = response;
return items_nota;
}
)
},
get: function (notaId) {
// Simple index lookup
var pepe = parseInt(notaId);
var ESTO = 0;
var addToArray = true;
for (var i = 0; i < items_nota.length; i++) {
if (items_nota[i].id == pepe) {
addToArray = false;
ESTO = i;
}
}
return items_nota[ESTO];
}
}
}])
This is my controller.js..
.controller('ActulidadCtrl', function ($q, $scope, NotasService, $timeout) {
var items_nota;
NotasService.all().then(function (data) {
$scope.items_nota = data;
})
//Pull tu refresh
$scope.doRefresh = function () {
console.log('Actualizando!');
$timeout(function () {
//NotasService.loadData().then(function (data) {
NotasService.all().then(function (data) {
$scope.items_nota = data;
})
//Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
};
})
Thanks! And Happy New Year!
UPDATE: solved the problem was in the server side cache
I think your problem is with GET query:
http://192.168.1.0:8100/wp-json/posts?filter[post_status]=publish&filter[posts_per_page]=30
Please check if this query is returning same posts event if you add new data.You can make sample http query using tools like Postman.
post_status and posts_per_page are constant.
Please check. Good luck!!

AngularJS Controller to update $scope automatically when backend data changes

I have a Service which uses $http to 'get' some JSON data from a REST API. The Controller uses the Service to get this data and initialise it in the $scope. How can I make it so that every time the JSON API changes that change is updated in the $scope, and thus the view?
Controller:
app.controller('MainController', function ($scope, BuildService) {
init();
function init() {
BuildService.getBuilds().then(function() {
$scope.builds = BuildService.data();
});
}
});
Service:
app.service('BuildService', function ($http, $q) {
var BuildService = {};
var deffered = $q.defer();
var data = [];
BuildService.getBuilds = function () {
//return builds;
$http.get('/api').
success(function(d, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
data = d;
deffered.resolve();
}).
error(function(d, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
deffered.reject();
});
return deffered.promise;
};
BuildService.data = function() { return data; };
return BuildService;
});
This question is not AngularJS-specific. What you want to achieve is a real-time app.
Method 1: polling
Use $interval to check JSON API every 30 seconds or so.
Method 2: WebSocket-based notification
If you have control over the JSON API, you can create another WebSocket-based notification API. Whenever JSON API changes, notify client to fetch JSON API again.
I'd say you really have too much unneccessary logic. Keep it simple and just go like that. If you want to reuse the GET you can do it in a getBuilds controller method.
app.controller('MainController', function ($scope, $http, BuildService) {
init();
function init() {
$http.get('/api').
success(function(data) {
$scope.builds = data;
});
}
});

Getting Json data in the Angularjs Scope

This is my first attempt at using Angularjs framework. I am trying to follow this example: http://jsfiddle.net/SAWsA/11/
I am successfully able to get the data in the Json format and it works fine.
json data:
[{"Activity_Matrix_ID":"163","Activity_ID":"131","Activity_Date":"2062-02-16","Activity_Category":"Maintanence","Activity_Project":"All Projects","Activity_Description":"Json data ","Activity_Hours":"2"},{"Activity_Matrix_ID":"161","Activity_ID":"129","Activity_Date":"2044-02-25","Activity_Category":"Tech Support","Activity_Project":"All Projects","Activity_Description":"Dummy dummy ","Activity_Hours":""}]
So basically, I want to load the data in $scope.items. I am not sure if it is the good method. I can visit the url and the data looks fine. I am stuck at getting the json correctly from the URL to the angular scope.
I tried following
<script type="text/javascript">
var sortingOrder = 'Activity_Projects';
</script>
<script>
function ctrlRead($scope, $filter) {
$scope.myData = function(item, event) {
var responsePromise = $http.get({method: 'GET', url: 'https://url_root_same_domain/timesheet/timesheet_info_table_json.php'}).success(function(data, status, headers, config) {
$scope.items = data;
console.log(data);
}).
error(function(data, status, headers, config) {
alert("No data");
});
}
</script>
Try this:
var responsePromise = $http.get('https://url_root_same_domain/timesheet/timesheet_info_table_json.php').success(...rest of your code here
The $http.get() function's first argument is a URL; not an object; and the method of a get call is already get, so you shouldn't have to do any other changes.

Categories

Resources