Angular promise回调不是在构造函数方法内部触发,而是在对象文本方法中触发

Angular promise callback not firing inside constructor method, but firing in object literal method

本文关键字:文本方法 对象 方法 回调 promise 构造函数 Angular 内部      更新时间:2024-05-17

让我们假设一个角度服务封装了一个纯Javascript模型。它有一个简单的异步方法,它使用promise解析返回接收到的相同参数(仅用于演示)。

angular.module('app', [])
  .factory('MyModel', ['$q', function ($q) {
    function MyModelConstructor() {
      this.test = function(myParam) {
        var deferred = $q.defer();
        if (myParam) {
          // Not triggering then callback
          deferred.resolve(myParam);
        }
        return deferred.promise;
      }
    }
    return MyModelConstructor;
  }]);

在调用测试方法之后,回调永远不会被触发。然而,如果我将测试方法作为文本附加到构造函数创建的对象上,那么一切都很好:

it('should not fail!!!', function() {
  myModelExample = new MyModel();
  var result;
  expect(result).toBeUndefined();
  myModelExample.test(111).then(function(funresult) {
    result = funesult;
  });
  $rootScope.$apply();
  expect(result).toBe(111); // But it fails
});
it('should have working promise', function() {
  myModelExample = new MyModel();
  var result;
  expect(result).toBeUndefined();
  myModelExample.test = function(myParam) {
    var deferred = $q.defer();
      if (myParam) {
        deferred.resolve(myParam);
      }
      return deferred.promise;
  }
  myModelExample.test(111).then(function(funresult) {
    result = funresult;
  });
  $rootScope.$apply();
  expect(result).toBe(111); // This way does not fail
});

构造函数创建的方法和字面方法在触发回调方面有什么区别?构造函数中附加的测试方法如何触发回调?

这是一个Plunker的例子

您有两件事错了:一个打字错误

result = funesult;

而且你还没有在测试中定义myModelExample,所以

myModelExample = new MyModel();

Plnkr:http://plnkr.co/edit/YdsuoJMkrccPjMb3e2jC?p=preview

您应该在.then内部进行测试。.then$rootScope.apply() 上发射

  it('should not fail but it fails!!!', function() {
    var result;
    myModelExample = new MyModel();
    expect(result).toBeUndefined();
    myModelExample.test(111).then(function(funresult) {
      result = funresult;
      expect(result).toBe(111); // NOPE :(
    });
    $rootScope.$apply();
  });

Plnkr:http://plnkr.co/edit/UWBvHorznTdPHrsxA2Hb?p=preview

这是一个正在工作的plunker:http://plnkr.co/edit/w3lDprPJVk6HSVSpXI7i?p=preview

1) 测试中未实例化MyModel。2) $rootScope.$applyexpect应该在promise回调内部