AngularJS - 使用外部工厂获取$ http GET请求 - 如何正确返回结果?

时间:2014-08-14 09:38:15

标签: angularjs http service get angularjs-scope

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

目前我正在将$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);

});

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

您可以创建一个返回角度$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*/       
});