2016-07-26 184 views
0

我的代碼有問題,我似乎不知道如何以及在何處放置代碼以向本地服務器發出$ 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; 

日上午在編程,所以請糾正我的小錯誤。

回答

0

創建一個constant.js文件(它將保留所有的常量和API URL)。創建一個服務/工廠。服務/工廠將通過API調用來提供數據。保持所有的http調用(服務內)。您可以爲每個控制器提供單獨的服務,或者可以爲所有控制器提供單一服務(取決於您想要的乾淨代碼)。從控制器:調用服務方法來獲取數據。服務將返回承諾。使用該承諾,您可以在控制器中獲取數據。 $ http調用返回承諾(它內置於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"))); 
+0

實施例因此這意味着我需要一個服務或一個工廠,將服務數據,如果我的每個服務從控制器,其中,我會需要它們分開?在app.js或api.js中@RajRj – JAEL

+0

U可以創建儘可能多的服務。只要你需要,將它們注入你的控制器。一旦服務可用於您的控制器,您可以調用在「服務」內定義的方法,這將返回「承諾」。我已經分享了「dataService」是具有getEmp()方法的我的SERVICE的例子。在控制器中注入「dataService」並調用getEmp()方法(如:var then = dataService.getEmp())。 現在你有PROMISE「THEN」使用你可以獲得數據。按照示例更清晰。你可以創建一個名爲「services」的文件夾,你將在其中編寫所有的服務JS文件 –