I am trying to build a food search app. I am using Angular and Spring. I am currently using the yelp API, but it's done on the Java side.
I think what I have achieved is really bad design. It works, but the data is not always updated correctly.
For Java, I created two methods and one string variable:
private String response;
@RequestMapping(value = "/searchRestaurant", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public void searchRestaurantWithYelp(@RequestBody String jsonData) {
//here i process the json string and pass the values to yelp function,
// then yelp sends the respond as a json string, i assigned the value
// to the response variable.
response = queryYelp();
}
As you can see, this post request receive a json string from client side, and pass the string to the yelp java API I created. The yelp respond is a json string, and I assign it to the response variable.
I also created a GET method, which simply returns the response, which contains the data yelp returned. I want to immediately return this data to the client/browser, with angular.
@RequestMapping(value = "restaurantResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String returnRestaurantSearchResultWithYelp() {
return response;
}
Now for my JS/angular side of code:
function HomeCtrl($scope, $http) {
$scope.term = "";
$scope.location = "";
$scope.submitSearch = function () {
var data = {
term: $scope.term,
location: $scope.location
}; //end data
var res = $http.post('/searchRestaurant', data);
$http.get('/restaurantResult').
success(function (data) {
$scope.response = data;
});
}
}
I wrapped a $http.get
inside the $http.post
. This function first sends data, which invoke my Java post method, then retrieves the data right after. I am binding the json data with angular so my app is single page. And with angular two way data binding the {{response}}
contains the yelp response and will display instantly to the user.
My simplified HTML:
<input type="text" ng-model="term"/>
<input type="text" ng-model="location"/>
<button ng-click="submitSearch()">Search</button>
{{response}}
It works, sort of. But I feel there is a better way to do it.
The issue: The {{response}}
sometimes cannot be updated instantly. For instance, I search burger king, the response will show me the address, location, etc. Then I type McDonalds, the response still shows the info of Burger King. I have to refresh the browser to get the latest and correct response.
I was wondering what the issue is causing the response not update instantly? Is it because of browser cache?
In terms of the my project build design, what part I did wrong? Is there a better way to handle this type of request?