Is it possible to utilize rxjs to exclude elements from an Observable based on a string array of identifiers?

When configuring Access Control for my Angular app, I have structured the User object as follows: -User --firstName --phoneNumber --posts[] <--- String array of post id's

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

To display only the posts associated with the user, I need the getPosts Observable to filter and return the post ids stored in the User's post array when subscribed.

Answer №1

retrieveUserPosts(): Observable<any[]> {
    const loggedInUser: User = JSON.parse(localStorage.getItem('user'));
    const userPosts  = loggedInUser.posts;
    return this.postsCollection.snapshotChanges().pipe(
      map((actions) => {
        return actions.map((a) => {
          const postDetails = { id: a.payload.doc.id, ...postDetails};
          const filteredPosts = _.filter(postDetails, (p) => 
          _.includes(loggedInUser, p.postId));
          return filteredPosts;
        });
      })
    );
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue3 and Typescript issue: The property '$el' is not recognized on type 'void'. What is the correct way to access every existing tag type in the DOM?

Currently, I am in the process of migrating a Vue2 project to Vue3 and Typescript. While encountering several unusual errors, one particular issue with $el has me puzzled. I have been attempting to target every <g> tag within the provided template, ...

Is it possible for me to create a union type that connects parameters and responses in a cohesive manner

I'm interested in creating a custom type that functions can use to indicate to callers that an input parameter of a specific type corresponds to a certain output type. For instance, consider the following scenario: type ResponseMap = { requestPath: ...

Optional parameters in typed languages can either have zero or all parameters provided

I am delving into the world of typed functional programming and have embarked on implementing partial application with a focus on type safety. Issue at hand: I'm aiming to create a function that can take a function along with zero or all of its param ...

Angular Module Federation upgrade error: "Schematics map not found in collection."

I am currently in the process of upgrading several Angular applications from version 12 to version 16. These applications utilize Module Federation along with the module federation plugin developed by Angular Architects. As I progress through each app and ...

Can the dimensions of a dialog be customized in Angular Material Design for Angular 5?

I am currently developing a login feature for an Angular 5 application. As part of this, I have implemented an Angular Material Design popup. Within the dialog screen, I have a specific process in place: The system checks the user's email to determi ...

Having trouble accessing / encountering an error in Angular 6 and .NET Core 2.1 integration

While working on my Angular form in the Visual Studio .NET Core 2.1 template, I encountered an issue with displaying toast notifications. When running localhost, I received a "Cannot GET /" error. Additionally, after running ng build, various errors appear ...

Does C# have an equivalent to TypeScript's Never type?

Is there a C# equivalent for TypeScript's never type? I am curious about this. For example, in TypeScript, if I write the following code, I will get a build time error: enum ActionTypes { Add, Remove } type IAdd = {type: ActionTypes.Add}; t ...

Determine whether there are three or more identical values when comparing two objects in typescript

Hello there, I am in need of some assistance as I am unsure where to begin. Any help would be greatly appreciated. Here are the two objects I have: const Questions = { five: "c" four: "c" one: "a" three: "a" two ...

Invoking a function on an object of a subclass that derives from an abstract class

In the realm of abstract classes, behold this one: export abstract class BaseStepComponent { /** Behold thy base-step ctor */ constructor() { } abstract getValue(): string; } And lo, here is a component that inherits such abstract glory ...

The error caused by Angular v6 is: "TypeError: Unable to access the 'map' property because

It seems that the response JSON is not mapping correctly as expected. Below is the HTML code: <h3>Enter Username</h3> <input (keyup)="search($event.target.value)" id="name" placeholder="Search"/> <ul> <li *ngFor="let package o ...

Creating a CSS class in a separate file for an element in Angular 4

Looking for some help with my code setup. Here's what I have: <div class="over"> Content </div> In my component file, this is what it looks like: @Component({ selector: 'app', templateUrl: './app.componen ...

Changing the row property value of a textarea dynamically based on text input in ReactJS

Here is what I have tried: <textarea rows='2' onChange={e => setSomething(e.target.value)} className='form-control text-area ' value={something} placeholder='write something'> </textarea> output: https://i ...

There are missing dependencies for the designated entry point, "@vcd/ui-components."

Upon running the application with npm start from the branch named ryan-a11y-merge-to-master at https://github.com/juanmendes/vmware-cloud-director-ui-components, I encountered the following error. However, when I switch to the master branch, no errors are ...

Guide to verifying the existence of a specific object mapping in JavaScript

I am currently working with an object mapping called res.payload.data[0].tnxResponse. I need to verify that the res object contains a payload property which in turn has a data property and so on. I attempted to do this using the following code, but it resu ...

How can we effectively display the cookie value within the template by utilizing observables and selectors in conjunction with the ngx-cookie-service library?

I'm wondering if there's a seamless approach to leverage observables for dynamically retrieving a cookie value, essentially creating a "reactive" cookie. Although typical solutions involve utilizing this.cookieService.get("cookieName") within ser ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

Displaying rows in a mat-table based on a certain condition

Is there a way to only display data in the table if the status is 'done'? I attempted to remove the status, but it still shows the row. Any suggestions on how to achieve this? data { equipmentOrdered: 'laptop', qty: 1, s ...

Access a router and showcase a new URL in the browser using Angular 2

When using the router.navigate method to navigate to a specific path, it is possible to display a different URL in the browser than the one being navigated to. For example, if I want to navigate to the path /open/quote using this.router.navigate(['/o ...

Exporting key/value objects with React components as values in Typescript

I have a .tsx file where I need to export an object containing key/value pairs. Each value is going to be a React component used in another file. While I will have multiple key/value pairs, I'm focusing on just one at the moment. object.tsx import { ...

Endlessly receiving NPM Docx notifications

I am currently working on a project to develop a module for exporting docx files using the npm docx package. However, whenever I try to execute it, I encounter the following error message (despite having imported the necessary components). I have also chec ...