将angularjs与node api集成?

时间:2015-11-06 14:43:17

标签: javascript angularjs node.js mean

我的节点路由如下

SELECT poverty, E.country
FROM(
  SELECT COUNT(language) as langnum, country
  FROM "Language"
  GROUP BY country) AS conto
JOIN "Economy" AS E
ON E.country=conto.country
JOIN (
SELECT COUNT(language) as langnum, country
  FROM "Language"
  GROUP BY country ORDER BY 1 DESC LIMIT 1
) AS maxlang ON maxlang.langnum = conto.langnum
ORDER BY conto.langnum DESC

我的模特是

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

//var morgan = require('morgan');             // log requests to the console (express4)
//var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
var methodOverride = require('method-override');
var fs = require('fs');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

var mongoose   = require('mongoose');

mongoose.connect('mongodb://localhost/test');

var User    = require('./models/users');
var Dummy    = require('./models/dummycar');

//app.use(express.static(__dirname + '/'));                 // set the static files location /public/img will be /img for users
//app.use(morgan('dev'));                                         // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                     // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());


// get users list

    app.get('/api/users',function(req, res) {
        User.find(function(err, users) {
            if (err)
                res.send(err);

            res.json(users);
        });
    });


//create users

    app.post('/api/users', function(req, res) {

        var user = new User();
        user.username = req.body.username;
        user.password = req.body.password;


        user.save(function(err) {
            if (err)
                res.send(err);

            User.find(function(err, users) {
                if (err)
                    res.send(err);
                res.json(users);
            });

        });
    });



//create cars

    app.post('/api/cars', function(req, res) {

        var dummy = new Dummy();
        dummy.name = req.body.name;
        dummy.brand = req.body.brand;
        dummy.class = req.body.class;
        dummy.price = req.body.price;
        dummy.available = req.body.available;



        dummy.save(function(err) {
            if (err)
                res.send(err);
            res.send("sucess");

        });
    });

//list cars

    app.get('/api/cars',function(req, res) {
        Dummy.find(function(err, dummys) {
            if (err)
                res.send(err);

            res.json(dummys);
        });
    });




//list cars by available

app.get('/api/cars/available',function(req, res) {
    Dummy.find({available:'true'},function(err, dummys) {
        if (err)
            res.send(err);

        res.json(dummys);
    });
});


// list cars by class


    app.get('/api/cars/:classtype',function(req, res) {
       Dummy.find({class:req.params.classtype}, function(err,dummys) {
            if (err)
                res.send(err);
            res.json(dummys);
        });


    });


// list cars by price

    app.get('/api/cars/price/:startvalue/:endvalue',function(req, res) {
        Dummy.find({price:{$gte:req.params.startvalue,$lte:req.params.endvalue}}, function(err,dummys) {
            if (err)
                res.send(err);
            res.json(dummys);
        });


    });


// booking option by sending date and name


    app.get('/api/cars/book/:nametype',function(req, res) {


        Dummy.findOne({name:req.params.nametype}, function(err, dummy) {

            if (err)
                res.send(err);

            dummy.available = false;


            dummy.save(function(err) {
                if (err)
                    res.send(err);

                res.send("updated");
            });

        });
    });


// user authentication

    app.get('/api/users/:usernametype/:passwordtype',function(req, res) {

        User.findOne({$and:[{username:req.params.usernametype},{password:req.params.passwordtype}]}, function(err, user) {
            if (err)
                res.send(err);
            else {
                if (user == null)
                    res.send(false);
                else
                    res.send(true);
            }

        });
    });







// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
//app.use('/api', router);

// application -------------------------------------------------------------

   app.get('*', function(req, res) {
        res.sendfile('./view/intro.html'); // load the single view file (angular will handle the page changes on the front-end)
    });

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('server running on  ' + port);

但我不知道如何从angular.js中调用它们

我的intro.html如下所示

//dummycar.js
var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;


var dummySchema = new Schema({
    name: {
        type: String,
        required: true
    },
    brand: {
        type: String
    },
    class: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    available: {
        type: Boolean,
        required: true
    },

    dateavailable: {
        type: Date,
        default:Date.now    }
});



module.exports = mongoose.model('Dummy', dummySchema);



//user.js
var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var userSchema = new Schema({
    username: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
});





module.exports = mongoose.model('User', userSchema);

我想在用户点击每个链接时给他们打电话。如果有人可以帮我开发angularjs服务。

1 个答案:

答案 0 :(得分:0)

最好是创建服务,但你可以在ctrl aswell

中完成
// users.service.js
var userService = angular.module('app.userService', ['ngResource'])
.factory('users', function ($http, $q) {
    var that = this;
    this.data = {};
    var url = '';

    var factory = {
        get: get
    };

    function get() {
        url = '/api/users';
        var defer = $q.defer();

        $http.get(url).
            success(function (data, status, headers, config) {
                defer.resolve(data);
            }).
            error(function (data, status, headers, config) {
                defer.reject(data);
            });
        return defer.promise;
    };
});

// some.controller.js
angular.module('app.somectrl', ['app.userService'])
    .controller(someController);

function someController(userService) {
    userService.get().then(function (res) {
        // do sth
    }, function (err) {
       // handle error
    });
}