【问题标题】:AngularJS - Using an external Factory for a $http GET Request - How to return the result properly?AngularJS - 为 $http GET 请求使用外部工厂 - 如何正确返回结果?
【发布时间】:2014-08-14 09:38:14
【问题描述】:

经过几次尝试,我现在可以访问外部服务工厂(被告知分散它是一个好习惯)来检索产品数据并将它们显示在我的视图中。

目前我正在将 $scope 传递给函数,这看起来有点丑陋(尤其是如果您添加更多的 CRUD 方法)。

有没有更好/更合适的方法来实现这一点?

提前致谢。

目前我使用它,如下所示(正在工作):

services.js

angular.module('services', [])
.constant("baseDataUrl", "http://localhost:55451/api/")
.factory('sportsstoreService', function ($http, baseDataUrl) {

    var serviceApi = {};

    serviceApi.getProducts = function ($scope) {
         $http({ method: 'GET', url: baseDataUrl + 'product' }).
         success(function (data, status, headers, config) {
              $scope.data.products = data;
         }).
         error(function (data, status, headers, config) {
             // called asynchronously if an error occurs
             // or server returns response with an error status.
         });
    };

    return serviceApi;        
});

sportsstore.js

angular.module("sportsStore")
    .controller("sportsStoreCtrl", function ($scope, sportsstoreService) {

        $scope.data = {};

        sportsstoreService.getProducts($scope);

});

【问题讨论】:

标签: angularjs http service get angularjs-scope


【解决方案1】:

更改您的服务,以便该函数返回一个承诺,如下所示:

serviceApi.getProducts = function () {
  return $http
    .get(baseDataUrl + 'product')
    .then(
      function success (response) {
        return response.data;
      },
      function error (reason) {
        // Do something!
      }
    );
};

然后在你的控制器中:

$scope.data = sportsstoreService.getProducts();

有关承诺的信息:

https://egghead.io/lessons/angularjs-promises

https://egghead.io/lessons/angularjs-chained-promises

https://docs.angularjs.org/api/ng/service/$q

【讨论】:

    【解决方案2】:

    您可以创建一个工厂,该工厂将返回 Angular 的 $resource 对象。 Angular $resource 对象具有默认操作:

     { 'get':    {method:'GET'},
        'save':   {method:'POST'},
        'query':  {method:'GET', isArray:true},
        'remove': {method:'DELETE'},
        'delete': {method:'DELETE'} };
    

    但您可以使用自己的自定义操作来扩展它们。在这里阅读更多:https://docs.angularjs.org/api/ngResource/service/%24resource

    有一个例子:

    .factory('SportsStoreService', function ($http, baseDataUrl) {
        var serviceApiCustomMethods={};
    
        serviceApiCustomMethods.getSimillarItems ={
            method: 'GET',
            url: baseDataUrl + 'product/simillar/:id',
            isArray: true
        };
    
        return $resource(baseDataUrl + 'product/:id',{}, serviceApiCustomMethods);
    
    });
    

    及用法:

    app.controller('ctrl',function($scope,SportsStoreService){
    
        SportsStoreService.query(function(response){
            //success
        },function(response){
            //error
        });
    
        SportsStoreService.get({id:'123'},function(response){
            //success
        },function(response){
            //error
        });
    
        SportsStoreService.getSimillarItems({id:'456',additionalGetParam: 5, anotherParam: desc},function(response){
          //success
        }); /*url's :id will be replacad with given id value because it matches url param in method declaration. 
           Rest of params will be added as GET params - ?additionalGetParam=5&anotherParam=desc*/       
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      相关资源
      最近更新 更多