简体   繁体   English

良好的做法是在角度中使用全局对象

[英]Good practice to use global objects in angular

I'm creating desktop app using nw.js framework with angular. 我正在使用带有angular的nw.js框架创建桌面应用程序。 In my controllers, services etc. i often use Node.js modules like this: 在我的控制器,服务等中,我经常使用如下的Node.js模块:

module.exports = function(ngModule) {
    ngModule.service('User', ['$q', function ($q) {
        var self = this;
        var fs = require('fs');
        var path = require('path');
        var gui = require('nw.gui');
    }]);
};

Is this a good practice ? 这是一个好习惯吗? Or maybe better create some service or put modules in $ rootScope ? 还是更好地创建一些服务或将模块放入$ rootScope

Generally require s should not remain within service constructor (unless they are conditional): 通常, require不应保留在服务构造函数中(除非它们是有条件的):

var fs = require('fs');
var path = require('path');
var gui = require('nw.gui');

ngModule.service('User', ['$q', function ($q) {
  ...
}]);

The code above will require to use packages like proxyquire to mock Node modules and test the service in isolation. 上面的代码将要求使用诸如proxyquire程序包来模拟Node模块并proxyquire测试服务。

DI is supposed to introduce additional flexibility and testability to the application. DI应该为应用程序带来额外的灵活性和可测试性。 Having the dependencies in separate module that can be easily stubbed is generally preferable way to handle this: 将依赖项放在可以轻松进行存根的单独模块中通常是解决此问题的首选方法:

angular.module('node', [])
.constant('gui', require('nw.gui'))
...

...

angular.module('app', ['node'])
.service('User', function ($q, gui, ...) {
  ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM