我克隆了一个https://github.com/beeman/loopback-angular-admin并且我使用loopback explorer创建了几个新角色,我试图通过loaded
操作挂钩登录特定用户的所有角色在这里定义 -
https://docs.strongloop.com/display/public/LB/Operation+hooks#Operationhooks-loaded
像这样 -
user.observe('loaded', function appendRole(ctx, next){
if(ctx.instance){
user.findOne({
where: {
id: ctx.instance.id
},
include: {
"relation":"roles"
}
})
}
next();
})
那么如何使用操作挂钩返回特定用户的角色。我可以使用此api调用
获取使用loopback explorer的用户的所有角色http://localhost:80/api/users/567ce48d6503f9404b56bb3e/roles?access_token=gyPzW3rpr3uzve2bUHtZQWv8iV5PfZYW7QLicCs4GwIKTdNA33SeRAlgPIQef7AE
UPDATE
:
所以,我尝试将以下代码添加到user.js -
user.observe('loaded', function appendRole(ctx, next){
if(ctx.instance){
console.log(ctx.instance.roles);
}
next();
})
我在控制台中获得以下输出 -
{ [Function]
_receiver:
{ username: 'harshitladdha93@gmail.com',
password: '$2a$10$Bubhaq1LXFyCUn.W1/pEOewLSqspcP2GQlONwGH98V4HqCOAc9522',
email: 'harshitladdha93@gmail.com',
status: 'created',
created: Mon Jan 04 2016 22:53:53 GMT+0530 (IST),
firstName: 'Harshit',
lastName: 'Laddha',
gender: 'male',
birthday: '1993-07-30T18:30:00.000Z',
qualification: 'sa;',
experience: 'askjdl',
achievements: 'sakldj',
street: 'has',
locality: 'alskjd',
area: 'lkjd',
city: 'bangalore',
id: 568aaaa997ace4670b5d9ac2 },
_scope:
{ where: { principalId: 568aaaa997ace4670b5d9ac2 },
collect: 'role',
include: 'role' },
_targetClass: 'Role',
getAsync: [Function],
build: [Function: build],
create: [Function],
updateAll: [Function: updateAll],
destroyAll: [Function: destroyAll],
findById: [Function],
findOne: [Function: findOne],
count: [Function: count],
destroy: [Function],
updateById: [Function],
exists: [Function],
add: [Function],
remove: [Function] }
那么如何使用加载的操作挂钩
获取用户的角色答案 0 :(得分:1)
你试过ctx.instance.roles
吗?
更新:哎呀,这是对的,我想你需要进行查找,但你不能使用user.find()
,因为它会触发一个无限循环装载观察。尝试这样的事情:
user.observe('loaded', function getRoleMappings(ctx, next) {
var roleMapFilter = {
where: {principalId: ctx.instance.id},
include: ['role']
};
user.app.models.RoleMapping.find(roleMapFilter, function(err, roleMaps) {
if (err) {
console.log('roleMap', err);
next(err);
}
console.log("roleMaps ", roleMaps);
next();
});
});
console.log("roleMaps ", roleMaps);
应该输出如下内容:
roleMaps [
{
id: 1,
principalType: 'USER',
principalId: '1',
roleId: 1,
role: {
id: 1,
name: 'admin',
description: null,
created: Thu Jun 25 2015 10:24:40 GMT-0700 (PDT),
modified: Thu Jun 25 2015 10:24:40 GMT-0700 (PDT)
}
},
{
id: 2,
principalType: 'USER',
principalId: '1',
roleId: 6,
role: {
id: 6,
name: 'sales',
description: null,
created: Thu Jun 25 2015 10:24:40 GMT-0700 (PDT),
modified: Thu Jun 25 2015 10:24:40 GMT-0700 (PDT)
}
}
]