Angular中的$资源如何工作

时间:2014-04-22 13:57:40

标签: angularjs rest

如果我有这样的网址" http:// x.x.x.x:port"

app.factory("myservice", function($resource){
    var res = function(){
        return $resource("http://x.x.x.x:port/profile/:userID", {
               {
                 getUserInfo: {
                                method: "GET",
                                params: {userID : "userNumber"},
                                headers:{
                                       "Accept": "application/json",
                                       "Content-Type": "application/json",
                                       sessionID : "sesionIDNumber"
                                }
                              }

                },
        });
    }

    console.log( res.get("firstName") );//error GET http://myurl/myport/profile?0=l&1=a&2=s&3=t&4=n&5=a&6=m&7=e&reg=%7B%2…2Fjson%22,%22sessionId%22:%22b1bfa646-215e-4223-be8c-b53d578ba379%22%7D%7D 404 (Not Found) 

});

如果我想获得用户的信息,我该怎么做?

1 个答案:

答案 0 :(得分:1)

你可以这样使用

app.factory("myservice", function($resource)
{
 return $resource('http://x.x.x.x:port/profile/:userID/:sessionID', {
        userID : '@userID'
        sessionID: "@sessionID"
        }); 
});

最好的例子如下所示

app.factory('Books', ['$resource', function($resource) {

    return $resource( '/book/:bookId', 
        { bookId: '@bookId' }, { 
            loan: { 
                method: 'PUT', 
                params: { bookId: '@bookId' }, 
                isArray: false 
            } 
            /* , method2: { ... } */
        } );
}]);

此时向Web服务发送请求非常简单,我们在之前的帖子中构建了。在任何地方都可以注入可以写入的Books服务:

postData = { 
  "id": 42, 
  "title": "The Hitchhiker's Guide to the Galaxy", 
  "authors": ["Douglas Adams"] 
}
Books.save({}, postData);
// It sends a POST request to /book. 
// postData are the additional post data

Books.get({bookId: 42});
// Get data about the book with id = 42

Books.query();
// It is still a GET request, but it points to /book, 
// so it is used to get the data about all the books

Books.loan({bookId: 42});
// It is a custom action.
// Update the data of the book with id = 42

Books.delete({bookId: 42});
// Delete data about the book with id = 42