将对象从express暴露到angularJS

Expose an object from express to angularJS

本文关键字:angularJS 暴露 express 对象      更新时间:2023-09-26

我想在Angular控制器中提供一个通过express检索的数据对象。现在我可以使用玉模板中的数据对象,如果我访问它的话…

#{data.mens.pants.jeans}

Express Code

api.get(query, options)
  .then(function(results) {
    log.info('api response received. rendering...');
    res.render('../mens/views/index', {
      data: {
        query: query,
        item: results
      }
    });
  })
  .error(function(err) {
    errors.renderError(res, err);
  });
 });

我不想要的

  • 进行另一个$http调用
  • 使用ng初始化

我尝试过使用.constant(),但常量只能包含字符串。

如何在角度控制器内部使来自express的对象可用。

提前感谢您抽出时间。

让我为您解释整个往返行程,从angular到express的请求,再到angular的响应。

您应该使用res.json(..)将数据发送回angular客户端,而不是使用res.render(..)[/strong>。如果您想使用好的promise,但我下面的示例是使用简单的回调。

api.get = function(req,res){
  //use req.params.<param_name> to get the parameter passed from angular.
    <some model>.someMethod({.params..},function(err,results){
        if(err){
            res.send(err);
        }
        res.json(results);
    });
};

假设您已经为上面的代码段定义了适当的路由,并使用http://localhost:3000/api/data/:id

因此,在前端Angular中,当您需要数据时,您可以使用$resource或$http服务来调用后端API。

var module = angular.module('app.services',['ngResource']);
module.factory('MyABCService',function($resource){
    return $resource('api/data/:id', 
    {
        id: '@id'
    },
    {
        'update': { method:'PUT' }
    },
    {
        'get': { method: 'GET', isArray: false }
    },
    {
        'delete': { method: 'DELETE'}
    }
);
});

现在在角度控制器中创建从API获取数据的方法。

$scope.searchABC = function(_id){
                $scope.myABCService = new MyABCService();
                $scope.myABCService.$get({id:_id},function(result){
                    //now AngularJS has two way data binding, so use result to assign values to your scope variables.
                }); 
}

如果您需要更详细的答案,请告诉我。