我的角度控制器出了什么问题?

时间:2017-08-19 14:25:29

标签: angularjs node.js

我用angular构建简单的nodejs restful api。服务器端(这是宁静的表达)工作没有问题我可以发布和删除或放置json输入没有问题,但一旦它到达前端,通过使用角度我面临一个问题。我无法从服务器获取数据我不知道为什么!!!

这是服务器端

appJs

// Tools to be used in the web development
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

//To connect it to the web front-end
app.use(express.static(__dirname+'/client'));
//To read data from forms
app.use(bodyParser.json());


//Models to be used
Genre = require('./models/genre.js');
Book = require('./models/book.js');


// Database Connection
let conn = mongoose.connection;
conn.openUri('mongodb://localhost/bookstore');

conn.on('error', err => console.error('mongodb connection error', 
err));
conn.on('connected', () => console.info(`Connected to mongodb`));
conn.on('disconnected', () => console.info('Disconnected from 
mongodb'));


// Routing to specific pages:

// Get requests
app.get('/', function(req, res){
res.send('Hello World');
});

app.get('/api/genres', function(req , res){
Genre.getGenres(function(err, genres){
    if(err){
        throw err;
    }
    res.json(genres);
})
});

app.get('/api/books', function(req , res){
Book.getBooks(function(err, books){
    if(err){
        throw err;
    }
    res.json(books);
})
});

app.get('/api/books/:_id', function(req , res){
Book.getBookById(req.params._id, function(err, book){
    if(err){
        throw err;
    }
    res.json(book);
})
});

//Post Requests
app.post('/api/genres', function(req , res){
var genre = req.body;
Genre.addGenre(genre, function(err, genre){
    if(err){
        throw err;
    }
    res.json(genre);
})
});


app.post('/api/books', function(req , res){
var book = req.body;
Book.addBook(book, function(err, book){
  if(err){
     throw err;
  }
  res.json(book);
})
});

//Put requests
app.put('/api/genres/:_id', function(req , res){
var id = req.params._id;
var genre = req.body;
Genre.updateGenre(id, genre,{}, function(err, genre){
    if(err){
        throw err;
    }
    res.json(genre);
})
});

app.put('/api/books/:_id', function(req , res){
var id = req.params._id;
var book = req.body;
Book.updateBook(id, book,{}, function(err, book){
    if(err){
        throw err;
    }
    res.json(book);
})
});

//Delete Requests
app.delete('/api/genres/:_id', function(req , res){
var id = req.params._id;
Genre.deleteGenre(id, function(err, genre){
    if(err){
        throw err;
    }
    res.json(genre);
})
});

app.delete('/api/books/:_id', function(req , res){
var id = req.params._id;
Book.deleteBook(id, function(err, book){
    if(err){
        throw err;
    }
    res.json(book);
})
});





//Specify the listening port
app.listen(3000);
//Display the url on the termianl
console.log('Server Running On http://localhost:3000');

这是来自前端angularJs

app.Js this for the routing

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function($routeProvider){
$routeProvider.when('/',{
    controller: 'BooksController',
    templateUrl: 'views/books.html'
})
.when('/books',{
    controller: 'BooksController',
    templateUrl: 'views/books.hrml'
})
.when('/books/details/:id',{
    controller: 'BooksController',
    templateUrl: 'views/book_details.html'
})
.when('/books/add', {
    controller: 'BooksController',
    templateUrl: 'views/add_book.html'
})
.when('/books/edit/:id', {
    controller: 'BooksController',
    templateUrl: 'views/edit_book.html'
})
.otherwise({
    redirectTo: '/'
})
});
来自前端angularJs的booksJs从服务器获取信息:提示:我认为来自这个文件的问题:

var myApp = angular.module('myApp');

myApp.controller('BooksController', ['$scope', '$http', '$location', 
'$routeParams', function($scope, $http, $location, $routeParams){
console.log('Books Controller loaded')


$scope.getBooks = function(){
    $http.get('/api/books').then(function(response){
        $scope.books = response.data;
    });
}
}]); 

这是显示bookJs数据并显示

的面板
<div class="panel panel-default" ng-init="getBooks">
<div class="panel-heading">
<h3 class="panel-title">Latest Books</h3>
</div>
<div class="panel-body">
<div class "row">
    <div ng-repeat="book in books">
        <div class="col-md-3">
            <div class="col-md-6">
                {{book.title}}
                <p>{{book.description}}</p>
            </div>
            <div class="col-md-6">
                <img src="{{book.image_url}}">
            </div>
        </div>
    </div>
</div>
</div>
</div>

这是主要的index.html

<html ng-app="myApp">
<head>
    <title>BookStore</title>

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>

    <nav class="navbar navbar-default">
  <a class="navbar-brand" href="#">BookStore</a>


  <div class="collapse navbar-collapse" id="navbar">
    <ul class="nav navbar-nav navbar-left">
      <li class="nav-item">
        <a class="nav-link" href="#!/books/add">Add Book</a>
      </li>     
    </ul>
  </div>
</nav>

<div class="container">

  <div class = "row">
      <div class ="col-md-12">

        <div ng-view></div>

      </div>
  </div>

</div><!-- /.container -->





    <script src="/bower_components/jquery/dist/jquery.js"></script>
    <script src="/bower_components/angular/angular.js"></script>
    <script src="/bower_components/angular-route/angular-route.js">
</script>
    <script src="/bower_components/bootstrap/js/bootstrap.js"></script>
    <script src="/app.js"></script>
    <script src="/controllers/books.js"></script>
    <script src="/controllers/genres.js"></script>


</body>
</html>

我使用邮递员处理Get / api / books后得到的信息,证明问题不是来自后端:

PostMan

一旦我使用fronend运行:

ServerWithFrontRunning

看来books.html的面板工作从book.js获取数据有问题!有什么建议吗?

2 个答案:

答案 0 :(得分:1)

ng-init="getBooks"不会调用函数(缺少括号()),避免使用ng-init,而是从getBooks

中的controller函数调用它
myApp.controller('BooksController', ['$scope', '$http', '$location', 
'$routeParams', function($scope, $http, $location, $routeParams){
  console.log('Books Controller loaded')


  $scope.getBooks = function(){
    $http.get('/api/books').then(function(response){
        $scope.books = response.data;
    });
  }
  function init(){
     $scope.getBooks();
  }
  init();
}]); 

答案 1 :(得分:0)

应该是这样的:ng-init="getBooks()"

但是,最好使用init函数作为@Pankaj Parkar的答案并且不要使用ng-init指令。