Retrieve a user's ID and display their posts along with comments using Angular 6

How can I retrieve all users based on their user id, iterate through them, and display all posts and comments when a specific user is clicked?

You can fetch the posts from the following API: https://jsonplaceholder.typicode.com/posts

And you can get their comments from this API: https://jsonplaceholder.typicode.com/comments

Here is my example project on stackblitz: https://stackblitz.com/edit/angular-g5fqzi

getUserPosts(userId: number) {
  this.http.get(`${this._postsURL}`)

  //.pipe(filter(data => userId === userId))
  //this.http.get(`${this._postsURL}/${userId}`)
    .subscribe(data => {
     //this.UserPosts  = data;
      let resources = data[userId];
      this.UserPosts = resources;
      console.log(this.UserPosts);
    })

Answer №1

Hey Qusay, it seems like you're looking to retrieve posts belonging to a specific userId.

If you're initiating a fresh HTTP request, you can include the userId parameter in the query to fetch only the desired posts:

this.http.get(`${this._postsURL}?userId=${userId}`)
  .subscribe(data => {
    // perform actions
  });

However, if you already have all the posts stored in memory and wish to select those associated with a specific userId, you can achieve this by:

const userPosts = this._postsArray.filter(post => post.userId == userId);

Alternatively, if there will always be just one result, consider using the find method instead of filter. Note that find returns the value while filter creates a new array with the values:

const userPosts = this._postsArray.find(post => post.userId == userId);

I trust this clarifies your query.

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

Validate an array of strings using Typescript custom type

Recently, I attempted to verify whether a variable is a custom type made up of different strings. I came across this helpful post Typescript: Check "typeof" against custom type that explains how to create a validator for this specific type. cons ...

The ability to choose only one option in a checkbox within a grid view column

In my grid view, I have a checkbox in the last column. I am trying to ensure that only one row can be selected at a time. <tr *ngFor="let permit of PermitDetails" (click)="GoByClick(permit)"> <td style="text-align: center">{{permit.TVA_BAT ...

Setting up the Angular environment

I am currently working on setting up the Angular environment for a project that was created by another individual. As I try to install all the necessary dependencies, I keep encountering the following error: https://i.sstatic.net/9knbD.png After some inv ...

What sets apart the Partial and Optional operators in Typescript?

interface I1 { x: number; y: string; } interface I2 { x?: number; y?: string; } const tmp1: Partial<I1> = {}, tmp2: I2 = {}; Can you spot a clear distinction between these two entities, as demonstrated in the above code snippet? ...

Is the Dropbox JavaScript SDK compatible with Ionic3?

Does anyone know how to integrate the Dropbox JavaScript SDK into an Ionic 3 app? Just a note: I have come across some sample examples using the http endpoint. ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

Combining numbers of identical precedence levels in JavaScript/jQuery

Suppose I have an array stored as follows: [1,2,3,4,5,6,7,9] My desired output is a string containing: "{1 to 7;9}" Currently, my code looks like this: var _checkbox = [1,2,3,4,5,6,7,9]; for (i=0; i<_checkbox.length; i++) { //if ($($(_checkbox) ...

Utilizing Javascript to extract information from JSON

After making an AJAX call, I have received a string in JSon format: {status:OK,addresses:[0,1,2,3,4,5]} In order to convert it into a JSon object, I tried using the following line of code: var jsonObj = eval(jsonString); However, this resulted in an ex ...

Looking for a solution to dynamically fill a list in JQuery with data from a JSON file. Any suggestions for troubleshooting?

Currently, I am utilizing a JSON file to fetch Quiz questions. In my approach, each question is being stored in an array as an object. The structure of the question object includes 'text' (the actual question), 'choices' (an array of po ...

What is the best way to retrieve specific JSON data from an array in JavaScript using jQuery, especially when the property is

Forgive me if this question seems basic, I am new to learning javascript. I am currently working on a school project that involves using the holiday API. When querying with just the country and year, the JSON data I receive looks like the example below. ...

Updating an object property within an array in Angular Typescript does not reflect changes in the view

I am currently delving into Typescript and Angular, and I have encountered an issue where my view does not update when I try to modify a value in an array that is assigned to an object I defined. I have a feeling that it might be related to the context b ...

The window:beforeunload event in IE 11 always triggers the unsaved changes dialogue box

When it comes to adding a listener for the beforeunload event on the global window object, IE 11 behaves differently compared to Chrome and Firefox. This is particularly noticeable when using Angular's "ngForm" module. If a form is dirty and has not ...

Looking for a shell script to retrieve the IP addresses of services running on a Kubernetes cluster

In my current project on VSTS, I am working on creating a release definition. My task involves extracting the external IP address of the service being deployed using Shell Script. While I have successfully executed this from the command line, I am facing c ...

Leveraging Json.Net's ContractResolver alongside inner reference properties

During the development of our API, we encountered a need to filter out certain properties of a model that are not accessible to the requesting user. We managed to fulfill this requirement using Json.Net ContractResolver. public class ConverterContractRes ...

Having trouble getting Chutzpah to work with TypeScript references

I am currently working on a project where my project folder contains the following files: chai.d.ts chai.js mocha.d.ts mocha.js appTest.ts appTest.js chutzpah.json The chai and mocha files were acquired through bower and tsd. Let's take a look at ...

Unable to generate image list in Listview in Flutter

I'm having trouble displaying images from a JSON source in a list. It seems like there's an issue with parsing the images correctly. Whenever I try to access an image from a nested list, I keep getting an error stating that 'list' is no ...

Steps for accessing and extracting data from a JSON file to a Json Array (JArray)

Currently, I am in the process of creating a Web API controller in C# ASP.NET MVC that accesses a JSON file containing a JSON array structured as follows: [ { "age": 0, "id": "motorola-xoom-with-wi-fi" }, { "age": 1, "id": "moto ...

Exploring API information in Ionic 4

Looking to retrieve data from the API, specifically using PHP on the backend. While I can access the data successfully, I'm running into an issue with *ngFor and the search bar functionality. The search button only appears when the input in the search ...

Put Angular4 (Angular) that has been developed with angular-cli onto Google App Engine

After creating an Angular4 application using Angular-CLI, I was able to run it locally with "ng serve" and everything worked perfectly. Now my goal is to deploy it to Google App Engine, where ng build --prod compiles all files into a dist folder. My quest ...

What is the best way to leverage TypeScript for destructuring from a sophisticated type structure?

Let's consider a scenario where I have a React functional component that I want to implement using props that are destructured for consistency with other components. The component in question is a checkbox that serves two roles based on the amount of ...