使用Angular访问Express的响应数据

Accessing response data from Express using Angular

本文关键字:响应 数据 Express Angular 访问 使用      更新时间:2023-09-26

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

这是来自Node.js.上Express的响应

routes/dashboard.js

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

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

views/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')

但是,我想避免这样做。

public/javascripts/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指令的需要。我该如何取回它?

一个更简单、也许更优雅的解决方案是在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);
     });      
}]);