我可以使用rxjs针对ID的字符串数组过滤Observable吗

时间:2019-05-21 12:51:29

标签: angular typescript rxjs google-cloud-firestore

我为一个有角度的应用程序设置了访问控制,并为我的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。

1 个答案:

答案 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;
        });
      })
    );
  }