我正在使用laravel 5.
我的控制器中有自定义操作。根据自定义,我的意思是它不会被角度中的资源对象使用。以下是我的控制器的代码。
class ServicesController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function extras()
{
// code here
}
}
这是我在角度脚本中的服务代码。
(function() {
'use strict';
angular
.module('bam')
.factory('myservice', myservice);
function myservice($resource) {
// ngResource call to the API for the users
var Serviceb = $resource('services', {}, {
update: {
method: 'PUT'
},
extras: {
method: 'GET',
action: 'extras'
}
});
function getExtras(){
return Serviceb.query().$promise.then(function(results) {
return results;
}, function(error) {
console.log(error);
});
}
}
})();
现在,这里的query()
会将请求发送到laravel控制器中的index方法。如何使用extras()
方法访问getExtras()
操作?
答案 0 :(得分:1)
It looks like you're almost there try out the example below I tried to use what you have in your question, and added a few other custom endpoints as examples. You'll want a base URL set up similarly to the example so you can feed it an id out of your payload so $resource can set up your base CRUD. Otherwise to make custom routes using the same resource endpoint you can add some extra actions like you have in your question, but apply your customization on the base endpoints URL.
.factory('ServicesResource', ['$resource',
function ($resource) {
// Parameters used in URL if found in payload
var paramDefaults = {
id: '@id',
param: '@param'
}
// Additional RESTful endpoints above base CRUD already in $resource
var actions = {
custom1: {
method: 'GET',
url: '/api/services/custom',
},
custom2: {
method: 'GET',
url: '/api/services/custom/:param',
},
extras: {
method: 'GET',
url: '/api/services/extras'
}
update: {
method: 'PUT'
}
}
// Default URL for base CRUD endpoints like get, save, etc
return $resource('/api/services/:id', paramDefaults, actions);
}])
Now you can dependency inject the factory and use it like this:
var payload = {param:'someParam'};
ServicesResource.custom(payload).$promise.then(function(response){
// handle success
}, function(reason) {
// handle error
});
Or for Extras:
ServicesResource.extras().$promise.then(function(response){
// Handle success
}, function(reason) {
// Handle error
});
In Laravel you're route might be something like this:
Route::get('services/{param}/custom', 'ServicesController@custom');
Or for extras like this:
Route::get('services/extras', 'ServicesController@extras');
答案 1 :(得分:0)
我使用$http
得到了我想要的东西。
function getExtras(){
return $http.get('/services/extras').success(function (results) {
return results;
});
}
但是,如果有人建议我如何使用Serviceb.query().$promise.then
。