如何与工厂进行回调

时间:2016-04-26 08:54:04

标签: angularjs

这是我的角度控制器的一种方法:

            $scope.callJersey = function(shows) {
            var selectedShows = [];
            var show;
            for (show in shows) {
                var temp = {};
                temp.name = show;
                temp.properties = shows[show].selectedShow;
                selectedShows.push(temp);
            }
            addShowsFactory.save(selectedShows);
        }

我的工厂:

services.factory('addShowsFactory', function ($resource) {
    return $resource('/easyshow/api/shows/add', {}, {
        save: {
            method: 'POST',
            isArray: true
        }
    })
});

当save方法完成工作时,如何进行回调? 我尝试了几种方法来显示警报(后来将是重定向),但没有任何效果。

2 个答案:

答案 0 :(得分:0)

让我用一些测试代码证明$promise



angular
  .module('shows', ['ngResource'])
  .factory('addShowsFactory', function($resource) {
    return $resource('/easyshow/api/shows/add', {}, {
      save: {
        method: 'POST',
        isArray: true
      }
    })
  });

describe("Shows", function() {
  beforeEach(module("shows"));

  it("adds shows", inject(function(addShowsFactory, $httpBackend) {
    var stubMovies = [{name: 'some name'}, {name: 'some other name'}];
    
    $httpBackend.expectPOST("/easyshow/api/shows/add").respond(201, stubMovies);
    
    addShowsFactory.save().$promise.then(function(shows) {
      expect(shows[0].name).toBe(stubMovies[0].name)
    })
    
    $httpBackend.flush();
  }));
});

<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>
&#13;
&#13;
&#13;

addShowsFactory.save返回承诺,您可以通过$promise属性访问它,然后就可以在其上调用then方法。

AngularJS documentation and exemple for $promise

答案 1 :(得分:0)

在进行一些测试后,这是一个有效的解决方案:

                $http.post('/easyshow/api/shows/add', selectedShows).then(
                    function(data){
                        alert("Yes");
                    }, function(data){
                        alert("No");
                    });

但是由于状态代码500总是返回,所以只调用错误函数。从不投降!!