简体   繁体   中英

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 :

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:

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

And sensorReadingCountFilter is as follows:

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'} ). I need a way to make this value be dinamic, using a variable, preferably being send from the AngularJS controller. I have several devices, with the portential to add even more, and don't want to create a /countFilter module for each of them.

In other words, a way to send variables from an AngularJS service to a NodeJS controller. 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.

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 .

You also can specify params in config object of $http:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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