Saturday, August 16, 2014

Refreshing server data in $http request in AngularJS

I'm getting along with my sample Angular project. One of the hurdles I had to take was refreshing my data after going from a list to a data form to change company data. Returning to the list would show the old data. Http requests get cached by the browser when the request string is the same as in a previous request.

Finally I found that generating unique keys with each http request was a simple solution to guarantee that  the http request was actually going to the rest server instead of returning the cached data.

I did it as following (javascript code):


var d = new Date();
var n = d.getTime(); // generate unique key
var httprequest="";
httprequest = "http://localhost:9080/ContractsRestServer/rest/RestCompanies/" + Orderby + "/" + n;
$http.get(httprequest)
        .success(function(data) {
            $scope.Companies=data
        }).error(function(data,status){alert("failure CompaniesController: HTTP code:" + status)});

Off course I also had to change my Java server side code to include the unique key. The signature of the class now looks as following:

package com.testres;

import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
// import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import ContractsDB.Models.*;

// http://localhost:9080/ContractsRestServer/rest/RestCompanies
// http://localhost:9080/ContractsRestServer/rest/RestCompanies/name    to order by name

@Path("RestCompanies")
public class GetCompanies {

 // This method is called if TEXT_PLAIN is request
 
 @GET 
 @Produces("application/json") // MediaType.APPLICATION_JSON)
 @Path("/{orderby}/{key}") 
 public String Get(@PathParam("orderby") String p_OrderBy,@PathParam("key") String p_Key) {
  System.out.println("in getcompanies + " + p_OrderBy  );
        Company_Factory cf = new Company_Factory();
        List<Company> Company_List = cf.QueryCompany("", p_OrderBy);       
        Gson gson = new GsonBuilder().create();
  return gson.toJson(Company_List); 
 }






When you want to cache your data, simply leave out the key.


No comments: