为什么你不能从另一个控制器方法中访问其他控制器方法呢?
像这样.
module.exports = findStore: -> # do somthing index: -> @findStore(); # Error: undefined
编译
module.exports = { findStore: function() {}, index: function() { return this.findStore(); // Error: undefined } };
如果你不能这样做,为什么不呢?我怎么能这样做......
在Sails中组织代码的最佳方法之一,至少对我和我的团队来说,一直是在服务(/ api/services)中拥有所有真正的业务逻辑.可以从任何控制器全局访问这些对象.
此外,一个好的做法是使用服务中的promise(因为Sails在模型方法上使用它们)
只需使用您的代码创建Store服务(StoreService.js):
module.exports = { findStore: function(storeId) { // here you call your models, add object security validation, etc... return Store.findOne(storeId); } };
您的控制器应处理与请求,调用服务和返回适当响应相关的所有内容.
例如,在您的示例中,控制器可以具有以下内容:
module.exports = { index: function(req, res) { if(req.param('id')) { StoreService.findStore(req.param('id')) .then(res.ok) .catch(res.serverError); } else { res.badRequest('Missing Store id'); } }, findStore: function(req, res) { if(req.param('id')) { StoreService.findStore(req.param('id')) .then(res.ok) .catch(res.serverError); } else { res.badRequest('Missing Store id'); } }, };
这样,您就拥有了非常简单的控制器,并且所有业务逻辑都由服务管理.
过去几个小时遇到同样的问题.我使用了api/services文件夹.它可能不是您需要的,但它是一个选项.这里有一个很好的解释.将哪些服务添加到sails.js中的api/services文件夹中
您可以使用 sails.controllers.yourControllerName.findStore()
在sails
全局对象参考了几乎所有的东西.