构建 angular 全栈 api 函数回调

structuring angular fullstack api function callbacks

我是 yeoman angular 全栈的新手,我的服务器 api 回调的结构似乎不正确。我已经破解了一些代码。我知道这是错误的,但我遇到了困难 - 任何建议将不胜感激:

例如,如果我进行简单的 win32ole iTunes com 调用和 return 文件路径:

在 client/app/main.controller.js

中调用 GET
  $http.get('/api/iTunes/getxmlpath').success(function(path) {
    $scope.myfilepath = path;
  });

路由设置在server/api/iTunes/index.js

router.get('/getxmlpath', controller.getxmlpath);

server/api/iTunes/iTunes的相关部分。controller.js

exports.getxmlpath = function(req, res) {
  getWin32OlePath(serviceCallback);
};

function getWin32OlePath() {
  try {
    var win32ole = require('win32ole');
    var iTunesApp = win32ole.client.Dispatch('iTunes.Application');
    var xmlpath = iTunesApp.LibraryXMLPath();
    console.log('got itunes xml path: '+xmlpath);
    return res.json(200, xmlpath);
  } catch (err) {
    return handleError(res, err);
  }
}


/********
error handle the callbacks
**********/
var serviceCallback =
function(response){
  return function(err, obj){
    if(err) {
      response.send(500);
    } else {
        response.send(obj);
      }
    }
  }

grunt 服务器失败

  Error: Route.get() requires callback functions but got a [object Undefined]

据我所知,上面的代码可能存在几个问题。 我将使用 lowercase 作为文件名和控制器,所以 itunes 而不是 iTunes:

  1. 你在server/routes.js中定义路由和控制器了吗?

    app.use('/api/itunes', require('./api/itunes'));

  2. 在 server/itunes/itunes.controller.js 中,您失去了响应对象的范围 res 您可以相应地更改代码:

    exports.getxmlpath = function(req, res) {
      var xmlpath = getWin32OlePath(serviceCallback);
      return res.json(200, xmlpath);
    };
    
    function getWin32OlePath() {
      var xmlpath = ''; // what ever you are doing here
    
      // do the things you need to do in your function
    
      return xmlpath;
    }
    
  3. 你server/itunes/index.js完成了吗?

    'use strict';
    
    var express = require('express');
    var controller = require('./itunes.controller');
    var router = express.Router();
    
    router.get('/getxmlpath', controller.getxmlpath);
    
    module.exports = router;
    

另一个提示:要使用 yeoman 轻松创建工作端点,您可以从终端使用生成器:

yo angular-fullstack:endpoint itunes

angular.fullstack 文档中有更多解释:https://github.com/DaftMonk/generator-angular-fullstack