如何将 $resource 转换为 $http?

4 浏览
0 Comments

如何将 $resource 转换为 $http?

如何将我对$resource的使用转换为利用原始的$http服务的方式?$resource$http有什么区别?

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

如何将我对$resource的使用转换为利用原始的$http服务的方式?$resource$http有什么区别?

0
0 Comments

从上述代码中可以看出,原来的代码中使用了$resource来处理HTTP请求。但是,由于某些原因,需要将$resource替换为$http。

原因:

1. $resource是AngularJS中的一个高级服务,用于处理RESTful API的请求。它提供了一种简单和一致的方式来定义和使用API。

2. 然而,$resource有一些限制和缺点。它对请求的处理方式比较固定,不够灵活。有时候需要更多的控制权和自定义能力。

解决方法:

1. 使用$http替代$resource。$http是AngularJS中的一个基本服务,用于发送HTTP请求。

2. 在原来的代码中,将所有使用$resource的地方替换为$http。具体操作包括:

- 将$resource.get()替换为$http.get()。例如,将$resource.get(API_LINK + '/api/users/' + id )替换为$http.get(API_LINK + '/api/users/' + id )

- 将$resource.put()替换为$http.put()。例如,将$resource.put(API_LINK + '/api/users/', {controller:'password'})替换为$http.put(API_LINK + '/api/users/', {controller:'password'}

3. 在替换后的代码中,将原来使用$resource的.success()和.error()方法替换为$http的.then()方法。例如,将.success(function(response) { defer.resolve(response); })替换为.then(function(response) { defer.resolve(response.data); })。同样,将.error(function(err) { console.log('err', err); defer.reject(err); })替换为.catch(function(err) { console.log('err', err); defer.reject(err); })

4. 在替换后的代码中,还需要添加一个defer对象来返回一个promise。例如,var defer = $q.defer();

通过以上步骤,就可以将原来使用$resource的代码转换为使用$http的代码。这样做的好处是,可以更灵活地处理HTTP请求,并且可以更好地控制和自定义请求的行为。

0
0 Comments

问题的出现原因:

问题的出现原因是因为想要将使用$resource编写的代码转换为使用$http来实现相同的功能。$resource是$ http的一个封装,旨在提供一种方便使用RESTful端点的API。然而,$http提供了更大的灵活性和控制权,因此可能需要将$resource转换为$http。

解决方法:

要将$resource转换为$http,可以将上述代码写入一个factory中,利用$http来实现相同的功能。以下是一个使用$http的factory示例:

// 假设API_LINK是一个可注入的常量
.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中使用此factory:

.controller('ctrl', function($scope, MyService) {
    MyService.get('me').then(function(response) {
        // ...
    });
    MyService.changePassword({ controller: 'password' }).then(function(response) {
        // ...
    });
});

如果需要完全控制factory函数和promise的解析过程,可以使用AngularJS的$q API。

关于id:@_id,应该将其放在请求URL中作为参数,例如:

return $http.get(API_LINK +'/api/users?id=' + id);

这将在URL中添加一个查询参数,用于指定要获取的用户的ID。

0