What is the method to extract a single user instead of a group of users?

I am attempting to transition from a list of users to displaying the profile of a single user on a separate page.

My goal is to achieve this using routerLink and passing the specific user's id to the next page.

Although the routing is functioning correctly as I am directed to the profile page, the issue arises when I log the results of the http request. Instead of receiving the details of one user, I still get back the entire list of users similar to the users page.

I have experimented with various solutions such as modifying the url path in my user.service.ts file, but it did not resolve the problem. In fact, I encountered 404 request errors when using the path ${this.url}/users/${id}/ instead of ${this.url}/users/?i=${id}/ which was working.

The API documentation suggests that in order to retrieve a single user, the format should be http://1234//users/{id}/, where id is an integer. However, when attempting to implement this format, the 404 error persisted.

Thus, I resorted to using the ?i= version, but the drawback is that only the full list of users is displayed on the next page.

MY CODE:

user.service.ts

// Obtain a user's profile
  getUserDetails(id): Observable<any> {
    return this.http.get(`${this.url}/users/?i=${id}/`); // why add ?i
  }

user.page.ts

// Retrieve all users in the users page
  getAllUsers() {
    this.userList = this.userService.getList()
    .pipe(map(response => response.results));
  }

user.page.html

<ion-avatar  class="user-image"  slot="start" [routerLink]="['/','profile', 'user.id']">
            <ion-img src="assets/22.jpeg"> </ion-img>
     </ion-avatar>

profile.page.ts

 information = null;
...
  ngOnInit() {
     // Extract the ID passed via URL
     let id = this.activatedRoute.snapshot.paramMap.get('id');

     // Fetch the information from the API
     this.userService.getUserDetails(id).subscribe(result => {
       this.information = result;
       console.log(result);
     });
   }

Answer №1

There seems to be an issue with the URL provided. If I were in your shoes, I would suggest logging the URL and comparing it with the documentation. Here's a code snippet that you can use to test some variations:

    const id = 1;

    const options = [
      `${this.url}/users/?i=${id}/`,
      `${this.url}/users/?i=${id}`,
      `${this.url}/users/i/${id}/`,
      `${this.url}/users/i/${id}`,
      `${this.url}/user/?i=${id}/`,
      `${this.url}/user/?i=${id}`,
      `${this.url}/user/i/${id}/`,
      `${this.url}/user/i/${id}`,
    ];

    for (const option of options) {
      try {
        const response = await this.http.get(option);
        console.log(options, response);
      } catch (e) {

      }
    }

You may also want to consider eliminating the second HTTP request. If the first request fetches all necessary data, you can simply store it in a variable within the service.

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

PHP is receiving data from $.post in an invalid format

I am facing a challenge in sending a JavaScript Object() to a PHP file in the correct format that $.POST requires. The PHP file does not establish any $_POST[] variables, which suggests that I may be transmitting the data in an improper format. JS: $(&ap ...

Build a custom Angular2 pipe to convert JSON data into an array through iteration

I am attempting to take the JSON data provided below and convert it into an array for use with *ngFor='let item of items', which will allow me to display data as item.name, etc... This is what I have tried: var out = []; for(var key1 in object) ...

Comparison of utilizing PHP within CSS versus Implementation through JavaScript [General]

Curious about the incorporation of PHP in CSS, especially in relation to my current Wordpress Theme project. I am aiming for high levels of customization and have been using a JS file to change CSS Properties through PHP. However, I'm not entirely con ...

iterating over a large multidimensional array in JavaScript

I am facing a challenge with handling a large JSON dataset (around 20k+ entries, totaling over 2mb) that I need to display on my web pages. Currently, I fetch this data using AJAX and parse it using JSON.parse in JavaScript, resulting in a complex multidi ...

Middleware transformation pipeline implemented using Typescript types

In my quest to create a function that empowers middlewares (specifically Express ones) to enhance the Request object by adding properties to it, I aim for subsequent middlewares in the chain to utilize these additions while preserving data types. An examp ...

Observable in Angular 2 that emits numbers

Currently, I am working on developing a countdown timer using AngularJS 2 that starts from n=60 seconds (i.e. hh:min:sec) My implementation includes the following code: countDown: Observable<number>; count = 60; constructor() { this.countDown = O ...

Unable to modify the color of the alert notification in JavaScript using React

I've been attempting to create an alert component, but I'm facing an issue with adjusting the color of the alert message. Upon enabling dark mode in the navbar (located at the bottom of the navbar component code), an alert message confirming the ...

How can we show a React JS component when clicked, without using the App.js file for display?

How can I display a component onclick in React JS without using UseState in a file other than App.js? This code will be in App.js var [clicks, setClicks] = useState(false) return( <> {clicks && &l ...

Unable to view videos shared by users in PeerJS and WebRTC video chat application from different tabs

Recently, I embarked on the task of creating a Video chat Website using Peer Js. Initially, everything seemed to be working fine as I was able to see my own video stream. However, a problem arose when attempting to view the video stream from another tab or ...

Access the outcome by utilizing a for loop

Within my code, I am utilizing both a function and a loop: var songs = Musics.searchSongs(query).then(function(rs) { return rs; }); for (var i = 0; i < songs.length; i++) { console.log(songs[i]); } I am now looking for a way to execute the ...

Exploring the Interaction Between Node.js and a Windows 10 Server on a Local Machine

I am curious about the interaction between Nodejs Server and a local machine. Specifically, I would like to understand how tasks such as: Thread Level CPU Cycle Socket Level IO Any help in clarifying this process would be greatly appreciated. ...

Issues with fundamental JavaScript client-side code

As a newcomer to the world of javascript and jQuery, I am diving into my first experiment with javascript. My initial focus has been on changing questions by clicking next or previous buttons. The goal is to create a dynamic quiz webpage that updates quest ...

Using .map() with a union type of string[] or string[][] results in a syntax error

interface Props { data: string[] | string[][]; } function Component({ data }: Props) { return data.map(v => v); } map() is causing an error: The expression is not callable. Each member of the union type '((callbackfn: (value: string, in ...

Utilizing PHP and JQuery Variables within the CodeIgniter Framework

Can someone please provide guidance on the best approach to handle this particular situation? I currently have a sidebar populated with Li Elements using a foreach loop, which is working perfectly. Each element contains a link that, when clicked, trigger ...

Implement the callback-console.log feature from the epic-games-api into an Express.js application

Looking to integrate Epic Games output into an Express.js GET request but don't have any JavaScript experience, so go easy on me! XD const EpicGamesAPI = require('epicgames-status'); const express = require('express') const app = ...

Changing images in vuejs

I am seeking to achieve a seamless transition between two images along with a corresponding legend. These images are sourced from an object-array collection. Since transitions operate only on single tags and components, I have devised a component to encap ...

Scrolling animations tailored to the navbar using jQuery

My fixed header contains a few links, and I've written some code that almost works perfectly. The issue is that there's a delay when the second function is executed. While it successfully scrolls to the top of the page when the linked element is ...

Unable to load additional posts at this time

Currently, I am working on implementing a LoadMore function that will add more posts based on the number of posts currently displayed and the total number of posts in the DOM. However, I am facing an issue where, upon console logging the listofposts and ...

Steps to resolving the 404 Not Found issue: nginx configuration with Angular and Keycloak

I am currently in the process of developing an Angular (10) application that utilizes Keycloak as its Identity and Access Management server. The general flow of the application is outlined below, https://i.sstatic.net/bs35F.png The URLs for the different ...

What could be causing the routing to fail in this script?

Currently working on a small project to dive into AngularJS, and I'm facing some challenges with getting the routing to function properly. Despite following numerous tutorials, my code doesn't seem to be working as expected. If anyone could lend ...