通过Nodejs脚本重用Angularjs服务和工厂

我的networking应用程序在客户端计算报价。 它利用Angular服务和工厂来实现这一点。

var myApp = angular.module("myApp"); myApp.service("quoteCalculator", function () { var calculator = { getPrice: function (quoteData) { return 402.56; } } return calculator; }); 

现在有一个需求,我需要在服务器端计算价格。 由于这个逻辑在JavaScript中,并且存在于Angular服务中,所以我不想在服务器端重复C#代码中的计算逻辑,原因很明显。

问题:使用Nodejs,有没有一种方法可以重用从Node.js脚本中调用的angular度服务“quoteCalculator”?

你可以用下面的代码实现你想要的。

 (function(is_node, is_angular) { function quoteCalculator(){ this.getPrice = function(){ return 402.56; }; } if (is_angular) { angular.module('my-service', []) .service('quoteCalculator', quoteCalculator); } else if (is_node) { module.exports.quoteCalculator = quoteCalculator; } })(typeof module !== 'undefined' && module.exports, typeof angular !== 'undefined' ); 

当我想在客户端和服务器之间共享一些逻辑时,我总是使用这个结构。 我希望它能帮助你。 🙂