在AngularJS Service中发出返回函数

时间:2014-06-05 04:02:50

标签: javascript angularjs angularjs-service

这是我的服务:

web.factory('distance', function() {
    Number.prototype.toRad = function() {
        return this * Math.PI / 180;
    };

    return function(origin, destination) {
        var R = 6371; // Radius of the earth in km
        var dLat = (origin.lat()-destination.lat()).toRad();  // Javascript functions in radians
        var dLon = (origin.lng()-destination.lng()).toRad();
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(origin.lat().toRad()) * Math.cos(destination.lat().toRad()) *
            Math.sin(dLon/2) * Math.sin(dLon/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        return R * c; // Distance in km
    };
});

在我的远程服务中返回功能正在轰炸。显然它看不到名为origin.lat()的方法。我认为在javascript中你不需要将任何东西初始化为类型先验?

以下是"origin.lat()":

首次出现时我遇到的错误
  

未捕获的TypeError:undefined不是函数

任何帮助表示赞赏。感谢

1 个答案:

答案 0 :(得分:1)

这里的错误是lat未被识别为' origin'上的函数。

现在你的工厂应该返回一个包含函数而不是函数的对象。

在将功能注入到您想要的任何地方后,您将执行对该功能的调用。

web.factory('distance', function() {

    // Should this be here???
    Number.prototype.toRad = function() {
        return this * Math.PI / 180;
    };

    return
        {
          calculate:function(origin, destination) {
                 var R = 6371; // Radius of the earth in km
                 var dLat = (origin.lat()-destination.lat()).toRad();  // Javascript functions in radians
                 var dLon = (origin.lng()-destination.lng()).toRad();
                 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                 Math.cos(origin.lat().toRad()) * Math.cos(destination.lat().toRad()) *
                 Math.sin(dLon/2) * Math.sin(dLon/2);
                 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                 return R * c; // Distance in km
        }
    };
});

您应该在您需要的地方使用:distance.calculate(a,b)