简体   繁体   中英

How can i communicate between angular and nodejs?

Node: app.js

var http = require("http");
var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/webshop';
var assert = require('assert');
mongoose.connect(url);
var products = mongoose.model('products', {
category: String,
type: String,
nme: String,
socket: Number,
clock: Number
});
app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});
app.use(express.static(__dirname + '/public'));
app.get('/products', function (req, res) {
    console.log("products");
    //Lets try to Find all products
    products.find(function (err, userObj) {
        if (err) {
            console.log(err);
            res.send(err);
        } else if (userObj) {
            console.log('Found:', userObj);
            res.json(userObj);
        //res.sendFile('views/aboutus.html', {root: 'public',data:userObj});
        } else {
            console.log('Products not found!');
        }
    });
});

products.html:

<!DOCTYPE html>
<html lang="en" ng-app="WebShop">
<head>
<meta charset="UTF-8">
<title>HELL</title>
<link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../bower_components/bootstrap/dist/css/bootstrap-theme.css" rel="stylesheet" type="text/css">
<link href="../stylesheets/style.css" rel="stylesheet">
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js">    </script>
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../javascripts/app.js"></script>
</head>
<body ng-controller="mainController">
<table>
    <tr>
        <th>Category</th>
        <th>Type</th>
        <th>Name</th>
        <th>Socket</th>
        <th>Clock</th>
    </tr>
    <tr ng-repeat="product in products">
        <td>{{product.category}}</td>
        <td>{{product.type}}</td>
        <td>{{product.name}}</td>
        <td>{{product.socket}}</td>
        <td>{{product.clock}}</td>
    </tr>
</table>
</body>
</html>

Angular:

var app = angular.module('WebShop', ['ngResource', 'ngRoute']);
app.controller('mainController',function($scope, $http,Products) {
var products = Products.get();
console.log(products);
$http.get('/products')
    .success(function (data) {
        console.log("http get products");
        $scope.products = data;
        console.log(data);
    })
    .error(function (data) {
        console.log('Error: ' + data);
    });
});

app.factory('Products', ['$resource', function($resource) {
return $resource('/products', null,
    {
        'get': { method:'get' }
    });
}]);

So my problem is...when i go to /products I get the json object on the webpage...but I would like to use the angular and the html file...so I would like to get the array in angular and i would like to view on the screen with using the products.html....but now i see just the array of objects. Can anybody helps to me? I think i not understand the communication between AngularJs and NodeJS. And I not really know how to send to angular and how to display the result with using html with angular tags/attributes. Thanks a lot!

You are returning a JSON user object as a response and expecting an array, JSON is javascript object notations, so it is like an associative array, it seems that you are using mongoDB as database which stores object in form of JSON. If you want to convert the JSON response to an array of properties as key value pairs you can refer: Converting JSON Object into Javascript array Or may be change the way you have written your service in nodejs. -V

If u return response as JSON then the following example can be used.

app.js

var express = require('express');
var app = express();
var path = require('path');

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.get('/products', function (req, res) {
    var products = {
        1: {
            name: "Product 1",
            description: "This is an awesome product"
        },
        2: {
            name: "Product 2",
            description: "This is also an awesome product"
        }
   };
   res.writeHead(200, {"Content-Type": "application/json"});
   res.end(JSON.stringify(products));
});

app.listen(3000);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular JS</title>
</head>
<body ng-app="myApp">
<div ng-controller="ProductController as product">
    <div ng-repeat="p in product">
        <h1>{{p.name}}</h1>
        <p>{{p.description}}</p>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script>
    var app = angular.module('myApp', []);
    app.controller('ProductController', function ($scope, $http) {
        $http.get("http://localhost:3000/products")
                .then(function (response) {
                    console.log(response.data);
                    $scope.product = response.data;
                });
    });
</script>
</body>
</html>

finally run

node app.js

and go to http://localhost:3000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM