AngularJS服务中的问题返回函数

Issue returning function in AngularJS Service

本文关键字:返回 函数 问题 服务 AngularJS      更新时间:2023-09-26

这是我的服务:

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()":第一次出现

Uncaught TypeError: undefined is not a function

感谢任何帮助。由于

这里的错误是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)