我想在我卑鄙的应用程序中将对象传递给控制器。我不太确定该怎么做。我正在使用中间件来检查用户是否是管理员。但是需要在控制器内获取当前用户。我目前正在使用Parse来获取登录用户,但是此操作始终返回null,有时还会带回admin用户帐户。 (不可靠)
路由器
const express = require('express')
const admin = require('../middlewares/admin')
const router = express.Router()
router.get('/', (req, res) => {
if (req.session.isAdmin){
res.redirect(req.baseUrl + '/places')
} else {
res.redirect(req.baseUrl + '/userplaces')
}
})
router.get('/userplaces', (req, res) => {
res.render('userplaces', req.session.user)
})
router.get('/places', admin, (req, res) => {
res.render('places')
})
控制器(这是我需要使用用户对象的地方)
'use strict';
angular.module('app')
.controller('UserPlaceCtrl',
function ($scope, $mdDialog, Toast, $translate, Place, Category, Auth) {
// Pagination options
$scope.rowOptions = [5, 25, 50];
$scope.query = {
canonical: '',
limit: 5,
page: 1,
total: 0,
isFeatured: null,
status: null,
category: null,
date: null,
user : Auth.getLoggedUser() // user user object here
};
身份验证服务(当前使用解析但未提供期望的结果)
angular.module('app').factory('Auth', function ($q) {
var mSessionToken = null;
return {
getLoggedUser: function () {
return Parse.User.current();
},
}
}
OR可以在这里在place服务中完成,并创建一个名为userplaces的方法。
angular.module('app').factory('Place', function ($q, moment) {
var Place = Parse.Object.extend('Place', {
initialize: function () {
this.images = [];
}
}, {
getInstance: function () {
return this;
},
save: function (obj) {
return obj.save();
},
delete: function (obj) {
return obj.destroy();
},
//create new method instead of all and add user query param
all: function (params) {
var query = new Parse.Query(this);
if (params.canonical != '') {
query.contains('canonical', params.canonical);
}
if (params.category && params.category !== null) {
query.equalTo('category', params.category);
}
if (params.date && params.date !== null) {
var start = moment(params.date).startOf('day');
var end = moment(params.date).endOf('day');
query.greaterThanOrEqualTo('createdAt', start.toDate());
query.lessThanOrEqualTo('createdAt', end.toDate());
}
if (params.status && params.status !== null) {
query.equalTo('status', params.status);
}
if (params.isFeatured && params.isFeatured !== null) {
query.equalTo('isFeatured', params.isFeatured);
}
if (params.user) {
query.equalTo('user', params.user);
}
query.include('category')
query.descending('createdAt');
if (params && params.limit) {
query.limit(params.limit);
}
if (params && params.limit && params.page) {
query.skip((params.page * params.limit) - params.limit);
}
return query.find();
},
Inside Server.js
app.use((req, res, next) => {
res.locals.user = req.session.user
res.locals.isAdmin = req.session.isAdmin
res.locals.page = req.url.split('/').pop()
res.locals.appId = process.env.APP_ID
res.locals.appName = process.env.APP_NAME
res.locals.serverUrl = process.env.PUBLIC_SERVER_URL
res.locals.googleMapsApiKey = process.env.GOOGLE_MAPS_API_KEY
next()
})