MattP
MattP

Reputation: 589

How do I pass parameters from angular controller/service, to server route, to query database?

I am trying to pass parameters to my backend route that will query my database to find the appropriate information, without having to write duplicate code for hundreds of different items. My problem is: I'm only getting an empty array returned; no errors. Any thoughts?? Here is some code:

Data in Mongo:

Materials Collection

{"material_name": "Something"},
{"material_name": "Another Something"}

server/route:

app.get('/materials/:name', (req, res) => {
    if (req.params.name) {
        db.collection('materials').find({"material_name": req.params.name}).toArray(function(err, results) {
            res.json(results);
        });
    }
});

factory:

angular.module("marbleApp")

.factory('materialFactory', function($q, $http) {
    return {
        getMaterialStuff: function() {
            var deferred = $q.defer(),
            httpPromise = $http.get('/materials/:name');

            httpPromise.success(function(materials) {
                deferred.resolve(materials);
            })
            .error(function(error) {
                console.log('Error...');
            });
            return deferred.promise;
        }
    };
});

controller:

.controller('MatInfoCtrl', function($scope, materialFactory, $stateParams) {
    $scope.materialStuff = {};
    materialFactory.getMaterialStuff()
    .then(function(materials) {
        $scope.materialStuff = materials;
        console.log(materials);
    }, function(error) {
        console.log(error);
    });
    $scope.name = $stateParams.materialName;
    $scope.category_name = $stateParams.categoryId;
});

state:

.state('material', {
    url: '/materials/:name',
    templateUrl: '/public/views/partials-matInfo.html',
    controller: 'MatInfoCtrl'
  });

EDIT: Here is the route I'm using to query mongodb. I slipped a console.log in the, and the result is 'undefined'.... Any ideas why?? Something is obviously not connecting/being passed.

app.get('/material/:name', (req, res) => {
    db.collection('materials').find({"material_name": req.params.name}).toArray(function(err, results) {
        console.log(req.params.name);
        res.json(results);
    });
});

Upvotes: 0

Views: 465

Answers (3)

MattP
MattP

Reputation: 589

So I figured it out. I wasn't passing the material_name as a variable to be used by the controller, which then could be used as a parameter in the route/GET to database.

I used a ui-sref:

 <div class="col m3" dir-paginate="material in graniteStuff | itemsPerPage: 20">
          <a ui-sref="material({name: material.material_name})">

Then changed my controller to:

$scope.name = $stateParams.name;
    materialFactory.getMaterialStuff($scope.name)

Then passed that to my service:

getMaterialStuff: function(name) {
            var deferred = $q.defer(),
            httpPromise = $http.get('/material/' +name);

Which then passed the parameter to the route:

app.get('/material/:name', (req, res) => {
    db.collection('materials').find({"material_name": req.params.name}).toArray(function(err, results) {
        console.log(req.params.name);
        res.json(results);
    });
});

thanks for all the help!

Upvotes: 0

Shaishab Roy
Shaishab Roy

Reputation: 16805

when you will send a request to server for path app.get('/materials/:name' then you should call from your service with your name value instead of :name like $http.get('/materials/yourName')

you can follow :

In your controller

$scope.name = $stateParams.materialName;
materialFactory.getMaterialStuff($scope.name).then(function(response){
    console.log('success', response.data);// check success data
    //rest of code
}, function(response) {
   console.log('error', response.data);// check error data
})

and in your service/factory:

getMaterialStuff: function(name) {// get name from controller
    return $http.get('/materials/'+name); // used name
    //By default $http return promise so no need to use $q.defer()
}

server route:

app.get('/materials/:name', (req, res) => {
    console.log('param name =', req.params.name); // check request params name
    if (req.params.name) {
        db.collection('materials').find({"material_name": req.params.name}).toArray(function(err, results) {
            if(err) {
               return res.status(400).send(err); // if error return with error data
            }
            return res.status(200).send(results);// if success return result
        });
    }
});

Upvotes: 0

Brent Washburne
Brent Washburne

Reputation: 13158

Your request always asks for /materials/:name, it should replace :name with the actual name:

httpPromise = $http.get('/materials/:name');

Upvotes: 1

Related Questions