使用Angular从Express访问响应数据

时间:2014-09-20 18:31:14

标签: javascript node.js angularjs express

我想使用Angular从我的前端访问经过身份验证的用户数据。

这是Express on Node.js的回复。

路由/ dashboard.js

exports.build = function (req, res) {
    res.render('dashboard', {
        uid: req.user._id
    });
};

我目前通过uid指令获取ng-init

视图/ dashboard.jade

doctype html
html
  head
    title= title
    link(href='//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css', rel='stylesheet')
    link(rel='stylesheet', href='/stylesheets/style.css')
    block styles
  body(ng-app='App', ng-controller='MainCntrl', ng-init='setUId(#{JSON.stringify(uid)})')
    // some content
    script(src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js')
    script(src='//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js')
    script(src='//cdnjs.cloudflare.com/ajax/libs/q.js/1.0.1/q.js')
    script(src='//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js')
    script(src='/javascripts/ng-app.js')

但是,我想避免这样做。

公共/ Javascript角/ NG-app.js

var app = angular.module('App', []);

app.factory('User', function () {
    return {
        // Promise for retrieving JSON User data
        getProperties : function (id) {
            var deferred = Q.defer();
            $.getJSON('/api/user/' + id
            , function (data) {
                deferred.resolve(data);
            }).fail(function () {
                deferred.reject(true);
            });
            return deferred.promise;
        }
    };
});

app.controller('MainCntrl', ['$scope', '$http', 'User', function ($scope, $http, User) {
    $scope.uid, $scope.user;
    $scope.setUId = function (id) {
        $scope.uid = id;
    };
    $scope.initUser = function () {
        User.getProperties($scope.uid).then(function (user) {
            $scope.$apply(function () {
                $scope.user = user;
            });
        }, function (err) {
            console.log(err);
        });
    };
}]);

我想将此uid数据传递给Angular,而不必使用ng-init指令。有没有办法访问响应数据,类似于:

console.log(res.body.uid);

从响应中检索uid参数将不再需要ng-init指令。我该如何检索它?

1 个答案:

答案 0 :(得分:0)

更多,也许是优雅的解决方案是在URL中使用用户ID并映射路由以接受id

然后你的控制器看起来更像这个

app.controller('MainCntrl', ['$scope', '$http', 'User','$stateParams', function ($scope, $http, User, $stateParams) {       
    // NOTE: I do not know which route engine you're using, though you would inject
    // its parameters provider in here, to get access to the url parameter (userId) of the route
    // so for this example, i have assumed ng-router hence the injection of $stateParams
    // the getProperties() method here is assuming ng-routet

    User.getProperties($stateParams.id).then(function (user) {        
        $scope.user = user;
       }, function (err) {
        console.log(err);

     });      
}]);