如何从angular生成$ http请求

时间:2016-07-26 12:39:47

标签: javascript angularjs node.js express

我的代码有问题,我似乎不知道如何以及在何处放置代码以向本地服务器发出$ http请求。

api.js

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Place = mongoose.model('Place');

module.exports = function(app){
app.get('/api/place', function(req, res){
    Place.find(function (err, places){
        if (err)
            res.send(err);

        res.json(places);
    });
});
};


router.route('/place')

.post(function(req, res) {

var place = new Place();

place.name = req.body.name;
place.address = req.body.address;
place.created_at = req.body.created_at;

place.save(function(err){
    if (err){
        return res.status(500).send(err);
    }
    return res.json({message: 'Place added', place});
});

})

.get(function(req, res){

Place.find(function(err, place){
    if(err){
        return res.send(500, err);
    }
    return res.status(200).send({place: place});
});


});

router.route('/place/:id')

.get(function(req, res){
Place.findById(req.params.id, function(err, place){
    if(err)
        return res.send(err);
    res.json(place);
});
})

.put(function(req, res){
Place.findById(req.params.id, function(err, place){
    if(err)
        res.send(err);
    place.name = req.body.name;
    place.address = req.body.address;
    place.created_at = req.body.created_at;

    place.save(function(err, place){
        if(err)
            res.send(err);
        res.json(place);


    });
});
})

.delete(function(req, res){
Place.findByIdAndRemove(req.params.id, function(err){
    if(err)
        res.send(err);
    res.json({message: 'Place removed!!!!!'});
});

});

module.exports = router;

的script.js

// script.js

// create the module and name it scotchApp
var app = angular.module('scotchApp', ['ngRoute', 'ngResource']);

// configure our routes
app.config(function($routeProvider){
    $routeProvider

       // route for the home page
        .when('/', {
            templateUrl : 'home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'contact.html',
            controller  : 'contactController'
        })

        //route for the contact page
        .when('/register', {
            templateUrl : 'register.html',
            controller : 'registerController'
        })

        //route for the login page
        .when('/sign-in', {
            templateUrl : 'sign-in.html',
            controller : 'signinController'
    });
});

app.factory('placeService', function($resource){
    return $resource('/api/place');
});
// create the controller and inject Angular's $scope
app.controller('mainController', function($scope, $rootScope, $http) {
    // create a message to display in our view

          /* $scope.place = placeService.query();
           $scope.newPlace = {name: '', address: '', created_at: ''};

           $scope.place = function(){
              $scope.newPlace.created_by = $rootScope.current_user;
              $scope.newPlace.created_at = Date.now();
              placeService.save($scope.newPlace, function(){ $scope.place =      placeService.query();
              $scope.newPlace = {name: '', address: '', created_at: ''};
               }); */   
     $http.get('/api/place').success(function(data){
        $scope.place = req.data.place;
        console.log(data);


    });
});


 app.controller('placesController', function($scope, $http) {
    var url = 'http://localhost:8080/api/places';
    $http.get(url).success(function(data){
        console.log(data);
    });
});

app.controller('aboutController', function($scope) {
    $scope.message = 'Look! I am an about page.';
});

app.controller('contactController', function($scope) {
    $scope.message = 'Contact us! JK. This is just a demo.';
}); 

app.controller('registerController', function($scope) {
    $scope.message = 'Join us! JK. This is just a demo.';
}); 

app.controller('signinController', function($scope) {
    $scope.message = 'Login. This is just a demo.';
});

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myproject');
require('./model/models')
var index = require('./routes/index');
var api = require('./routes/api');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/index', index);
app.use('/api', api);


var port = process.env.PORT || 8080;
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
  error: err
});
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
   message: err.message,
   error: {}
 });
});

app.listen(port);               

// shoutout to the user                     
console.log('Magic happens on port ' + port);
module.exports = app;

我是编程的初学者,所以请纠正我的小错误。

1 个答案:

答案 0 :(得分:0)

创建一个constant.js文件(它将保留所有常量和API URL)。创建服务/工厂。服务/工厂将通过API调用提供数据。将所有的http调用保存在(服务内部)中。您可以为每个控制器提供单独的服务,也可以为所有控制器提供单一服务(取决于您想要的干净代码)。来自控制器:调用服务方法来获取数据。服务将回报承诺。使用该承诺,您可以在控制器中获取数据。 $ http调用返回promise(它内置于Angular中)。

以下示例

    (function (module) {
                var appConstants = {

                    empApi: {
                        employee: 'your url to call(http://something.com/sfsadf)',
                    },

                };
                module.constant('appConstants', appConstants);

            }(angular.module("app")));


        (function (module) {

            module.factory("dataService", ["$http", "appConstants", 
function ($http, appConstants) {

                this.getEmp = function () {
                    return $http.get(appConstants.empApi.employee);
                };

                return this;
            }]);

        }(angular.module("app")));


    (function (module) {

        module.controller("empController", ["dataService", function (dataService) {    
            var _this = this;

            dataService.getEmp ().then(function(result){
                _this.data = result.data;
            });

        }]);

    }(angular.module("app")));