是否应该在 angular 服务中定义所有 RESTful API 调用?

Should ALL RESTful API calls be defined in an angular service?

我想调用以下 api 条路线

/api/user/:id
/api/user/inbox
/api/user/blah

是否所有这些都定义在一个 angular 服务中?我该怎么做?我看过的每个教程都有一个服务,它立即 returns 资源,它通常也用于 CRUD 操作。我很可能会在多个控制器中调用这些路由,所以我认为将它放在一项服务中是有益的。有人可以举例说明我将如何创建调用这些路由的服务吗?

我想在其他控制器上做这样的操作

$scope.inbox = $api.getUserInbox()  //function which requests api/user/inbox

$scope.user = $api.getUser()   //function which requests api/user/:id

$scope.blah = $api.getUserBlah() //function which requests api/user/blah

其中 $api 是我要定义的服务,getuserInbox() 是一个为 /api/user/inbox

发出 http 请求的函数

是的,将所有 RESTfull API 调用放入服务是理想的。好处包括:

  • URL 在一个地方,所以当更改 API(或使用不同的版本)时,您可以在一个地方更改它。
  • 可以轻松重构以使用替代 $http 例如:restangular。
  • 轻松为请求添加通用错误处理,因为所有请求都在一个地方。
  • 使测试更容易。只是 'mock' 你的 API 服务而不是搞乱 $httpBackend


app.service('userAPI', function($http) {
    var self = this;
    var baseUrl = "api/user/";

    self.getUser(id) {
        return $http.get(baseUrl + id);
    }
});

app.controller('myController', function($scope, userAPI) {
    userAPI.getUser(1).then(function(response) {
        $scope.user = response.data;
    };
}

PS - 如果您使用的是真正的 RESTfull API,我建议您考虑 Restangular.