0

i have some problems with angularJS and REST requests / responses. Since three weeks i playing with AngularJS and now i would like do some cool stuff. First i created a simple jersey REST service, that returns a simple list.

@Path("/hello")
public class Hello {


  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public List<Medication> sayJsonHello() {
      List<Object1> objs = new ArrayList<Object1>();

      objs.add(new Object1("1", "HUHU"));
      objs.add(new Object1("2", "HUHU 2"));

      return objs;
  }
}

as you can see, there is no big magic. Here my web.xml file, to configure Jersey:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     id="WebApp_ID" version="2.5">
<display-name>Jersey REST Example</display-name>
<servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>examples</param-value>
    </init-param>

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

    <init-param>
        <param-name>com.sun.jersey.config.feature.DisableWADL</param-name>
        <param-value>true</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

After some tests, the service will return a simple JSON list:

[
{
  "id": "1",
  "name": "HUHU"
},
{
  "id": "2",
  "name": "HUHU 2"
}
]

I deploying the webservice into a Tomcat7 instance. Now i would like to get this data into my webapplication. After reading some tutorials and example i starting to create few implementations.

After starting create my first service, i and this code-snipped into my app.js:

app.config(['$httpProvider', function ($httpProvider) {
    delete $httpProvider.defaults.headers.common["X-Requested-With"];
}]); 

this will remove X-Request-With request-header from the header defauls.

1. Request via Service and ngResource

angular.module('helloService', ['ngResource']).
    factory('hService', function ($resource) {

        return $resource('http://localhost\\:8180/rest/hello',
            {callback: 'JSON_CALLBACK'}, {
                get: {method: 'GET', headers: [
                    {'Content-Type': 'application/json'},
                    {'Accept': 'application/json'}
                ]}
            });
    });

MyController:

function MyController($scope, hService) {
    hService.get(function(result){
        alert(" Result of helloService");
    }, function error(response){
        alert(" Error during helloService "+response.status);
    }); 
}

if i try to load data, the get functin will always return an error and the status is always 0.

2. Trying with Restangular

After get how to use Restangular i starting to configured Restangular:

app.config(function (RestangularProvider) {
    RestangularProvider.setBaseUrl('http://localhost\\:8180/rest');
});

and also add the RestangularProvider to my angular.module:

var app = angular.module("html5App", ['helloService', 'restangular', 'ngResource']);

MyController:

function MyRestangularCtr($scope, Restangular){

    var all = Restangular.all('hello');
    $scope.allObjects = all.getList();

    all.getList().then(function (hellos) {
        console.log("Result "+ hellos);
    }, function errorCallback(response) {
        alert("Oops error from server :( status" + response.status);
        console.log("status: "+response);
    });
}

Here the same: No Data, Status 0. I have no idea, why i dont get any data from my service. Additional i getting sometimes this error: "Error: $digest already in progress". Im not sure, where the problem is. If the jersey service i wrong or bad or my beginner JavaScript is wrong.

First Solution

Client Side

The Angular request should look like this:

$scope.myData = $resource('http://localhost\\:8180/rest/:action',
    {action: 'hello', callback:'JSON_CALLBACK'},
    {get: {method: 'JSONP'}});
$scope.datas = $scope.myData.get();

The method need to JSONP (GET will still not working ( no repsonse data because CORPS?)

Service Side

Important here is, that the server also response with a JSONP fomat and can handle callback requests.

@GET
@Produces("application/x-javascript")
public JSONWithPadding sayJsonHello(@QueryParam("callback") String callback) {
    MyObjectList obList= new MyObjectList ();

    obList.getObjs().add(new MyObject(1, "HUHU"));
    obList.getObjs().add(new MyObject(2, "HUHU 2"));

    return new JSONWithPadding(obList, callback);
}

Still unclear

Is there any way to return normal json object from server to client?

5
  • What is \\:8180 and what do console/network say? Probably it's related to CORS. Commented May 29, 2013 at 8:43
  • localhost\\:8180 is wrong Commented May 29, 2013 at 8:45
  • why? $resource module stripping port :8888 from url groups.google.com/forum/?fromgroups#!topic/angular/18aO0bIlEm0 Restangular: github.com/mgonto/… Restangular uses $resource inside. $resource requires ports to be escaped to as not to think they are actually parameters. So the right way of setting a baseUrl with a port is the following: RestangularProvider.setBaseUrl('localhost\\:8080'); otherwise, the request will be send to localhost/rest/hello and not to my tomcat server. Commented May 29, 2013 at 10:00
  • about :8180 should not be a CORS issue, because is the same domain or not? Commented May 29, 2013 at 10:06
  • Don't know if this is still relevant but have you tried to disable web-security see how-to in this SO question Commented Jul 22, 2013 at 11:38

1 Answer 1

1

Shouldn't be the first parameter of you controller be $scope? Maybe this is the issue?

function MyController($scope, hService) {
Sign up to request clarification or add additional context in comments.

1 Comment

unfortunately no, same behavior. Is there any restriction, that i need to use as method "JSONP" or is method: 'GET' also valid to request JSON data from RESTfull service?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.