简体   繁体   English

如何从AngularJS服务发送变量到NodeJS控制器?

[英]How to send a variable to a NodeJS controller from an AngularJS service?

I have an AngularJS service called sensorReadingsAPI , which has the following function with get : 我有一个名为sensorReadingsAPI的AngularJS服务,该服务具有get的以下功能:

var _countSensorReadingsFilter = function () {
  return $http.get(config.baseUrl + "/sensorReading/countFilter").then(function (data,status) {
    sensorReadingCountFilter = data.data;
    return Number(sensorReadingCountFilter);
  }).catch(function() {});
};

The /countFilter is defined in a NodeJS controller: /countFilter/countFilter控制器中定义:

module.exports = {
  countFilter: function (req, res) {
    return res.sensorReadingCountFilter();
  }
};

And sensorReadingCountFilter is as follows: sensorReadingCountFilter如下:

module.exports = function sensorReadingCountFilter(statusCode){

  var req = this.req;
  var res = this.res;

  SensorReading.count({deviceNum:'MBA002'}).exec(function countCB(error, found) {
    return res.view({val: found});
  });
};

Right now, the count is static (where is written {deviceNum:'MBA002'} ). 目前,该计数是静态的(写在{deviceNum:'MBA002'} )。 I need a way to make this value be dinamic, using a variable, preferably being send from the AngularJS controller. 我需要一种使用变量使该值动态的方法,最好是从AngularJS控制器发送。 I have several devices, with the portential to add even more, and don't want to create a /countFilter module for each of them. 我有几个设备,可能会添加更多设备,并且不想为每个设备创建一个/countFilter模块。

In other words, a way to send variables from an AngularJS service to a NodeJS controller. 换句话说,一种将变量从AngularJS服务发送到NodeJS控制器的方法。 When searching for ways to do this, I have found next to nothing. 在寻找执行此操作的方法时,我几乎一无所获。

For clearance: all of this returns the number of readings from the selected device, and config.baseUrl is the local machine and port. 为了方便起见:所有这些都返回所选设备的读数数量,而config.baseUrl是本地计算机和端口。

You can use url parameters in your $http.get('url-here?param1=1,param2=2') and then you can access these params in your req object on the server side req.query.param1 . 您可以在$http.get('url-here?param1=1,param2=2')使用url参数,然后可以在服务器端req.query.param1 req对象中访问这些参数。

You also can specify params in config object of $http: 您还可以在$ http的配置对象中指定参数:

$http.get('my-url-here', { params: {deviceNum:'MBA002'} })
    .success()
    ...

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

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