简体   繁体   English

SailsJS从控制器访问服务

[英]SailsJS accessing a service from a controller

I am trying to create a service in sailsjs so I can access some business logic from within multiple controllers, I've stumbled upon a number of issues... The service is an 'Action log' I hope to log data about specific api calls to the database via a model. 我正在尝试在sailsjs中创建一个服务,所以我可以从多个控制器中访问一些业务逻辑,我偶然发现了一些问题...该服务是一个'动作日志'我希望记录有关特定api调用的数据通过模型到数据库。

The file structure I have: 我有的文件结构:

api/services/actionService.js - the service to receive data from controller and log to model
api/models/Action.js - functioning model to store logged actions
api/controllers/ActionController.js - functioning controller to respond to get requests for the action model
api/controllers/AnotherController.js - I wish to access the actionService from here to input data
  1. I am unsure how to reference the service from AnotherController.js; 我不确定如何从AnotherController.js引用该服务; according to the sails docs I should be able to call ActionService(data) but I get an ActionService is not defined error. 根据sails文档,我应该能够调用ActionService(data)但是我得到的ActionService is not defined错误。 Is there something I need to do to load this dependency in the controller? 有什么我需要做的事情来加载控制器中的这种依赖吗?

  2. Am I able to reference a model from within the service? 我能从服务中引用模型吗? At the moment I have something like Action.create(action)... in the service. 目前我在服务中有类似Action.create(action)...东西。 This hasn't caused problems yet as I haven't got passed the first issue but wondering whether I also need to load this as a dependency in the service? 这还没有引起问题,因为我还没有通过第一个问题,但想知道我是否还需要将其作为服务中的依赖项加载?

I'm new to implementing services in sailsjs, any help is appreciated. 我是sailsjs实施服务的新手,感谢任何帮助。

You can access your services in any controller using this syntax: 您可以使用以下语法在任何控制器中访问您的服务:

<yourServicefilename>.method();

In your case it would be actionService.<yourMethodName>() . 在您的情况下,它将是actionService.<yourMethodName>()

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

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