Angular 5 and RxJS to create a filtered array observable

I'm currently working on developing a basic forum.

One of the tasks at hand involves filtering the posts using RxJS and dealing with some challenges related to .pipe and .filter methods.

Here is what I am attempting to achieve:

  • Retrieve the list of posts from an in-memory API endpoint api/posts. The http.get method returns an Observable<Post[]>
  • Go through each individual post in the Observable<Post[]> and filter out only those posts with an id of 1 (assuming there is only one post with an id of 1)
  • Display any errors or success messages in the console

However, when applying the filter, it seems to be selecting the entire Post[] array instead of individual elements within the array.

This is my code snippet:

getPosts(): Observable<Post[]> {

  // Define the URL for the posts
  const url = this.postsUrl;

  // Using http.get to retrieve an Observable<Post[]>
  return this.http.get<Post[]>(url)
    .pipe(
      filter(
        post: Post => post.id == 1
      ),
      // Log success message
      tap(posts => console.log('Posts fetched.')),
      // Error handling
      catchError(this.handleError('getPosts', []))
    );
 }

The error I encountered:

Property 'id' does not exist on type 'Post[]'

In all the examples I've reviewed, the filter function was able to iterate through each value individually within the Post[] array. It should allow access to each element as a Post type.


Update following a solution suggestion

The final revised code segment, based on the provided solution, is structured as follows:

In posts.service.ts:

getPosts(): Observable<Post[]> {

  const url = this.postsUrl;

  // Get the observable containing an array of Posts
  return this.http.get<Post[]>(url)
    .pipe(
      // Log success message
      tap(posts => console.log('Posts fetched.')),
      // Error handling
      catchError(this.handleError('getPosts', []))
    );

}

In posts.component.ts:

private getPosts(): void {
  this.service.getPosts()
    // Mapping posts to a filtered version
    .map(
      posts => posts.filter(
        post => post.from_board_id == this.from_board_id
      )
    )
    // Subscribe to the results
    .subscribe(
      posts => this.posts = posts
    )
  ;
}

Answer №1

Observables represent a continuous flow of values. When using RXJS, you are essentially informing the library that you expect to receive a stream of Post[], which can be interpreted as an Array<Post>.

If you wish to apply filtering to the array, you could implement something along these lines:

 return this.http.get<Post[]>(url).map(posts => posts.filter(post => post.id === 1))

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

`ng build`: transferring scripts to a subdirectory

When running the command ng build, it exports files to the dist folder like this: index.html main.bundle.js styles.bundle.js ... I would like the scripts to be in a subfolder: *index.html scripts/main.bundle.js scripts/styles.bundle.js ...* ...

Error encountered while making an Angular POST request with object parameter

Need to make a post request to update the current user on the home page. The expected url for the post should be in this format: "http:......./user/id". However, when the request is sent, the url becomes "http:/...../user/[object%20Object]" which causes an ...

Tips for eliminating the page URL when printing a page using window.print() in JavaScript or Angular 4

Can someone help me with a function that uses window.print() to print the current page, but I need to remove the page URL when printing? I'm looking to exclude the URL from being printed and here is the code snippet where I want to make this adjustme ...

Using PropTypes in React Native with Typescript

Hey there, I'm currently working on a new app in React Native using TypeScript and TSX syntax. I have a question regarding defining a prop type function without resorting to using the "any" type. In JavaScript with PropTypes, I can define a prop type ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

How can data from a service function be accessed in an Angular component?

I am currently delving into learning Angular. Most things are working well, but some are not. In order to gain a deeper understanding, I have a question. Within my Component, I am receiving data from a function that calls JSON. Below is the snippet of code ...

How to retrieve all the days of each month starting from a particular day with the help of momentJS in Angular

I am currently working on developing a custom day picker that will show all the days of the month in a calendar format, displaying them from Sunday to Saturday. Currently, I am only able to display dates from the 1st of the month onwards. https://i.sstati ...

issue with angular material mat-accordion on click event not scrolling to the top

When the expansion panel header in Angular Material is clicked, the onExpand function is supposed to be called. However, at that time, the window scroll should move to the top or change position but this functionality is not working as expected. onExpan ...

Activate the function when the @Input() is modified

In my parent component, I have the following code in the parent.component.html: <app-child [idElement]=(idElement)></app-child> The child component has an input parameter defined as follows: @Input() idElement : number; Additionally, there ...

What is the best way to utilize ngStyle in combination with Interpolation?

Within my application, I am faced with a challenge involving two slide bars that generate values ranging from 1 to 100. Based on these generated values, I aim to adjust the margin of a div element in accordance with the percentage output. Despite conductin ...

What is the most efficient method for sharing types within an extensive TypeScript project?

I'm currently developing a complex React application using TypeScript. I have numerous common types defined in separate files, and I find myself importing them every time I need to use them. While this approach is functional, it results in a large num ...

Highlighting the selected value in an Angular Material mat option

I am looking to enhance the background color of the selected value when it is clicked. Unlike the example I found, which highlights multiple select values, I only want to highlight the selected value when choosing an option. Check out this example for ref ...

Issue with Multer s3 upload: File not functioning properly in s3 and size increase of file

I successfully uploaded an mp4 file to s3 using node.js and the code seems to be functioning well as I can see the file in s3. However, there seems to be a discrepancy in the file size. The original file is 860kb but after uploading it, it increases to 1.4 ...

Issue with TypeORM custom repository not successfully overriding the createQueryBuilder function

I have successfully implemented database i18n for TypeORM in theory. Now, I am looking to override built-in repository methods to incorporate i18n by intercepting them and adding a query. However, I am facing difficulties with overriding the createQueryBui ...

What is the best way to show a list of all users in Firebase, with their details, while excluding the current user who

The following code snippet displays a list of all users, except for the current logged-in user. This data will be used for display purposes and potentially for future searching. Typescript: public ngOnInit(): void { if (this._auth$.authenticated) ...

The 'jsx' property in tsconfig.json being overridden by Next.js and TypeScript

Is there a way to prevent NextJS from changing the 'jsx' property in my tsconfig.json file from 'react' to 'preserve' when running the development server? This is how my tsconfig.json file looks: "compilerOptions": { " ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

Show Index of an Array in Angular version 4 and above

I have implemented a drag and drop feature where elements are dragged and dropped into an array. The dragging functionality is contained in one component, with three different types of fields - text, number, and date - that can be dragged onto the form. On ...

Utilizing string to access property

Is there a better way to access interface/class properties using strings? Consider the following interface: interface Type { nestedProperty: { a: number b: number } } I want to set nested properties using array iteration: let myType: Type = ...

Angular's two-way binding feature does not seem to be updating the value for date

In my Angular - Dotnetcore 2.0 form, users are required to update their demographic information including their birth date. Initially, I was using the following code snippet to display the birthdate: <input id="dateOfBirth" type="date" class="form-cont ...