简体   繁体   English

MEAN.JS新的控制器功能和路由

[英]MEAN.JS New Controller Function and Route

I'm learning MEAN.JS and having a few issues with routing, just looking to add a new function to the articles project called getSubArticles which calls to the server and does something. 我正在学习MEAN.JS,并且在路由方面遇到了一些问题,只是想向article项目添加一个名为getSubArticles的新功能,该功能会调用服务器并执行某些操作。

    //articles.server.routes.js
    app.route('/articles/:articleId/subarticles')
            .get(articles.read);

    //articles.server.controller.js
    exports.read = function(req, res) {
        res.jsonp("My Sub articles");//just using for testing
    };

    //articles.client.controller.js
    $scope.getSubArticles = function() {
                // What goes here as everything I've tried has failed, but the route could be constructed incorrectly
            };

//articles.client.view.html
    <section id="subarticle-listing" data-ng-controller="ArticlesController" data-ng-init="getSubArticles()">

Any ideas where I'm going wrong? 有什么想法我要去哪里吗? Got a sample MEAN.JS project with non default routes/functions I can look at... 得到了一个带有非默认路由/功能的示例MEAN.JS项目,我可以看一下...

Cheers, Adrian 干杯,阿德里安

A few things jump out, first you should make sure your route is getting hit when requested, you can add a console.log in your read funciton. 有几件事情发生了,首先,您应该确保在被请求时遇到路由问题,您可以在读取函数中添加console.log。 In your app.js (or server.js, whichever file is used to start your app) you need to have: 在您的app.js(或server.js,用于启动应用程序的任何文件)中,您需要具备以下条件:

 //server.js file:
    var router = express.Router();    
    var routes = require('./articles.server.routes.js'); //path to your routes file
    router.use('/',routes);

In your articles.server.routes.js file, include these requires at the top, and your route can't have a variable then a fixed name afterwards, basically anything after the variable will get chopped off, so the new route should be: 在您的articles.server.routes.js文件中,在顶部包含这些要求,并且您的路由之后不能再有一个变量,而后要有一个固定的名称,基本上,该变量之后的所有内容都会被砍掉,因此新路由应为:

// articles.server.routes.js
var express = require('express'),
    app = express().Router();

 app.route('/articles/subarticles/:articleId')
                .get(articles.read);

In your articles.server.controller.js: 在您的articles.server.controller.js中:

 exports.read = function(req, res) {
        var articleid = req.params.bid
        console.log('read function called' + articleid)
        res.jsonp("My Sub articles");//just using for testing
    };

Now in your Angular controller: 现在在您的Angular控制器中:

$scope.getSubArticles = function() {
    $http.get('/articles/subarticles/' + $scope.articleId)

    .success(function(data){
        //do something with your return data
    }
    .error(function(err){
        //error handler
}
}

Hope that helps, if not, let me know and I can suggest a few more things. 希望能有所帮助,如果没有,请告诉我,我可以提出更多建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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