2014-10-07 65 views
0

我有兩個angularjs服務,他們應該調用不同的restful服務(第一個檢索單個用戶,第二個返回用戶數組)。爲什麼他們都在調用服務來獲得大量用戶?爲什麼我的兩個不同的angularjs服務解析爲相同的restful Java EE Web服務?

這裏有兩個angularjs服務:

angular.module('clearsoftDemoApp').factory('UserDetail', function ($resource) { 
return $resource('http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users/:id', {}, { 
    find: {method: 'GET', params: {id: '@id'}}, 
    update: { method: 'PUT', params: {id: '@id'} }, 
    delete: { method: 'DELETE', params: {id: '@id'} } 
}); 

});

angular.module('clearsoftDemoApp').factory('Users', function ($resource) { 
return $resource('http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users', {}, { 
    findAll: {method: 'GET', isArray: true} 
}); 

});

這裏是從Java RESTful服務的相關代碼:

@Stateless 
@Path("clearsoft.demo.users") 
public class UsersFacadeREST extends AbstractFacade<Users> { 
@PersistenceContext(unitName = "ClearsoftDemoBackendPU") 
private EntityManager em; 

public UsersFacadeREST() { 
    super(Users.class); 
} 

@GET 
@Path("{id}") 
@Produces({"application/xml", "application/json"}) 
public Users find(@PathParam("id") Integer id) { 
    return super.find(id); 
} 

@GET 
@Override 
@Produces({"application/xml", "application/json"}) 
public List<Users> findAll() { 
    return super.findAll(); 
} 

的問題是,當我運行此,既angularjs服務似乎調用的findAll()的Web服務,這是不是我的意圖。

回答

1

$resource意味着從端點檢索數據,操縱它並將其發回,並使用一組默認參數,這些參數可以在呼叫中明確覆蓋。 只需使用AngularJS內部資源的匹配過程,而不是定義到種源的功能,即只定義了第一UserDetails資源,並呼籲http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users的時候,那麼你會得到所有用戶加載。

爲此,您需要將:id定義爲可選參數。

一方面說明您可能需要添加[ngResource]模塊,因此不要忘記包含它。

var service = angular.module("clearsoftDemoApp", ["ngResource"]); 
// UserDetail Resource 
service.factory('UserDetail', function ($resource) { 
    return $resource(
    '/ClearsoftDemoBackend/webresources/clearsoft.demo.users/:id', 
    {id: "@id" }, 
    { 
     find: {method: 'GET'}, 
     update: { method: 'PUT'}, 
     delete: { method: 'DELETE'} 
    }); 
}); 

以下代碼段定義了一個UserDetail模塊,讓你火以下要求:

// Get all users 
var users = UserDetail.query(); // Calls: GET /ClearsoftDemoBackend/webresources/clearsoft.demo.users 

// Get user with iD 1 
var user = UserDetail.get({},{'id': 1}); // Calls: GET /ClearsoftDemoBackend/webresources/clearsoft.demo.users/1 

// Find user with iD 1 
var user = UserDetail.find({},{'id': 1}); // Calls: GET /ClearsoftDemoBackend/webresources/clearsoft.demo.users/1 
相關問題