2015-07-29 13 views
7

ho un angularJS $ risorsa:

$resource("http://localhost:3000/:id",{ 
    id: '@id' 
}, 
{ 
    get: { 
     method:'GET', 
     isArray: false 
    }, 
    foo: { 
     method:'POST', 
     url: 'http://localhost:3000/:id/foo', 
     isArray: false 
    } 
}); 

Ora, se io chiamo:

User.foo({id:'123', anotherParam: 'bar'}); 

Ciò si traduce nella URL 'http://localhost:3000/foo' essere chiamato e passando il i parametri id e anotherParam come campi POST.

In realtà desidero chiamare "http://localhost:3000/123/foo" e passare solo il parametro anotherParam come campo POST.

Come si ottiene il comportamento del parametro ID correttamente?

risposta

14

https://docs.angularjs.org/api/ngResource/service/$resource

non GET "di classe" azioni: Resource.action ([parametri], PostData, [il successo], [errore])

quello che devi fare:

User.foo({id:'123', anotherParam: 'bar'}, <post data object>); 

Quando si chiama la funzione con un singolo argomento. Presume che l'argomento facoltativo non è presente e lo invia come postData.

1

La soluzione accettata non ha funzionato per me (AngularJS v1.4.8). È necessario impostare manualmente il tipo di contenuto e trasformare per formare i dati.

Esempio:

var DirectoryApi = $resource('api/directories', null, { 
    move: { 
     url: 'api/directories/:name/_move', 
     params: {"name" : "@name"}, 
     headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, 
     transformRequest: function (param) { 
      return $.param(param); 
     }, 
     method: 'POST' 
    }, 
}); 

e di utilizzo:

function moveDirectory(name, parent, after) { 
    return DirectoryApi.move({name: name}, {parent: parent, after: after}); 
}