如何将$ resource转换为$ http?

时间:2016-01-12 05:21:27

标签: javascript angularjs ajax angularjs-service

如何使用$resource转换为使用原始$http服务? $resource究竟做$http到底是做什么的呢?

return $resource(API_LINK+'/api/users/', {
   id: '@_id'
 },
 {
   changePassword: {
     method: 'PUT',
     params: {
       controller:'password'
     }
   },
   get: {
     method: 'GET',
     params: {
       id:'me'
     }
   })

2 个答案:

答案 0 :(得分:2)

$resource只是对$http的抽象,认为API可以方便地用于RESTful端点。 $resource无法使用$http无法写入$http。在利用// assumption that API_LINK is an injectable constant .factory('MyService', function(API_LINK, $http) { function changePassword(params) { return $http.put(API_LINK +'/api/users/', params); } function get(id) { return $http.get(API_LINK +'/api/users?id=' + id); } return { changePassword: changePassword, get: get } }); 的工厂中编写上述内容的方法可能包括......

.controller('ctrl', function($scope, MyService) {

    MyService.get('me').then(function(response) {
        // ...
    });

    MyService.changePassword({ controller: 'password' }).then(function(response) {
        // ...
    });
});

具有以下用途......

     public function edit() {
    $id = $this->request->params['pass'][0];
    $this->Master->id = $id;
    if( $this->Master->exists()){
        if( $this->request->is( 'post' ) || $this->request->is( 'put' ) ){
            if( $this->Master->save( $this->request->data ) ){
                $this->redirect(array('action' => 'index'));
            }
            else { 
                $this->Session->setFlash('Unable to edit row. Please, try again');
            } 
        }
        else { 
          $this->request->data = $this->Master->read();
        }
    } 
}

如果您需要通过相关的承诺解决方案完全控制您的工厂功能,我建议您查看AngularJS $q API

答案 1 :(得分:0)

我们也可以采用其他方式:

Settings.canDrawOverlays(context);