Donovant
Donovant

Reputation: 3161

How does $resource in Angular work

If I have a url like this "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) 

});

If I want to get the user's infoes, what do I have to do?

Upvotes: 0

Views: 291

Answers (1)

Nidhish Krishnan
Nidhish Krishnan

Reputation: 20751

You can use like this

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

A best example is shown below

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

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

At this point it is really simple to send requests to the web service, that we build in the previous post.Everywhere it is possible to inject the Books service it is possible to write:

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

Upvotes: 1

Related Questions