我为一个有角度的应用程序设置了访问控制,并为我的User对象建模,如下所示: -用户 - 名字 - 电话号码 --posts [] <---帖子ID的字符串数组
getPosts(): Observable<any[]> {
return this.postsCollection.snapshotChanges().pipe(
map((actions) => {
return actions.map((a) => {
const data = a.payload.doc.data();
const data2 = { id: a.payload.doc.id, ...data};
this.hasPostAccess(data2);
return { id: a.payload.doc.id, ...data};
});
})
);
}
private hasPostAccess(data: any) {
const inspect = obj => {
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
// console.log(`${prop}: ${obj[prop]}`);
if (prop === 'id') {
console.log(obj[prop]);
const PostId = obj[prop];
const currentUser = JSON.stringify(localStorage.getItem('user'));
if (currentUser.search(PostId) === -1) {
console.log('Denied: ' + PostId);
} else {
console.log('Allowed: ' + PostId);
}
console.log('Current USER: ' + JSON.stringify(currentUser));
// if (currentUser(PostId) > -1) {
// console.log('Allowed: ' + PostId);
// } else {
// console.log('Denied: ' + PostId);
// }
}
}
}
};
inspect(data);
}
我想显示属于该用户的所有帖子。因此,当我订阅getPosts Observable时,这必须过滤帖子并仅返回存储在User帖子数组中的帖子ID。
答案 0 :(得分:0)
getPosts(): Observable<any[]> {
const currentUser: User = JSON.parse(localStorage.getItem('user'));
const userPosts = currentUser.posts;
return this.postsCollection.snapshotChanges().pipe(
map((actions) => {
return actions.map((a) => {
const data = { id: a.payload.doc.id, ...data};
const filteredPosts = _.filter(data, (p) =>
_.includes(currentUser, p.postId));
return filteredPosts;
});
})
);
}