【问题标题】:Using Angular $Resource what is the angular way to create a service using multiple api calls?使用 Angular $Resource 使用多个 api 调用创建服务的角度方式是什么?
【发布时间】:2016-02-15 11:50:50
【问题描述】:

我正在做一个 Angular 项目,我是第一次使用 $ 资源。我目前正在测试一项从我的数据库中获取数据的服务,该服务可以调用 $resource

这是我的服务:

(function() {
"use strict";
angular.module("commonServices")
    .factory("ptaResource",
    ["$resource", ptaResource]);

function ptaResource($resource) {
    return $resource("http://localhost:55928/api/excercises", {}, { 'query': { method: 'GET', isArray: true } });
}
})();

我的问题是这样的。我对这些控制器中的各种控制器和方法进行了很多调用。我不知道如何构建允许我使用列出的端点调用它的服务

我试着做这样的事情:

var services =[
    getExercises: getExercises,
    doSomething: doSomething
   ];
   return service;

    function getExercises (){
        return $resource request here
      }

但这不起作用,我在网上查看过,但任何教程都只公开了每种类型的请求中的一种。我将向控制器发出几个 get 请求,其中一些带有不同的查询字符串。我也会查询不同的控制器。我内心的纯粹主义者告诉我,所有这些都属于一个地方。

有什么方法可以单独调用每个请求来完成这项大型服务。我是否应该将它们分解为每个 Web api 控制器的服务。任何意见将不胜感激。

谢谢, 约翰

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    如果您想将资源包装在服务中,您可以执行以下操作:

    angular
        .module('commonServices', ['ngResource'])
        .factory('ptaResource', ['$resource', function($resource) {
            return $resource('http://localhost:55928/api/excercises/:excerciseId', {
                excerciseId: '@id'
            });
        }])
        .service('CommonService', ['ptaResource', function(ptaResource) {
            return {
                getExercises: function() {
                    return ptaResource.query().$promise;
                }
            };
        }]);
    

    那么你可以这样称呼它:

    angular
        .module('app', ['commonServices'])
        .controller('SomeController', ['$scope', 'CommonService', function($scope, CommonService) {
            $scope.exercises = CommonService.getExercises();
    
            // or
            CommonService.getExercises().then(function(exercises) {
                $scope.exercises = exercises;
            }).catch(function(err) {
                // handle error here
            });
        }]);
    

    【讨论】:

    • 好的,我正在关注你,现在我正在使用我的控制器来调用查询,但是你正在工厂调用下添加一个调用查询的服务。然后控制器调用命名函数。我这样做对吗?
    • 这是正确的。老实说,没有必要提供额外的服务,但我的印象是这就是你想要完成的目标
    • 谢谢,这很有意义
    猜你喜欢
    • 2014-09-15
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2020-03-11
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    相关资源
    最近更新 更多