What is the best method to retrieve the unique identifier of the user who is currently logged in

I'm currently facing an issue with accessing the data of the authenticated user in my code and figuring out how to fetch it.

I have completed the authentication flow, allowing users to register and login successfully with a token. Even after refreshing the page, the user remains logged in and the token is stored in the ionic/storage.

It seems like having the token should be sufficient to retrieve the specific user data/permissions. However, I am uncertain about how to accomplish this.

When viewing a user's profile by clicking on their profile tab, I can easily pass along their ID from a list. But how do I obtain the ID of the authenticated user just by clicking on the profile tab?

In this scenario, there isn't another page where I can retrieve the ID from. I have included my auth.service code for reference, which handles the token, but the key parts seem to be the last two snippets.

This is the snippet from auth.service.ts:

 private token = null;
  user = null;
  authenticationState = new BehaviorSubject(false);



  constructor(private http: HttpClient, private alertCtrl: AlertController, private storage: Storage, private helper: JwtHelperService,
              private plt: Platform) {
    this.plt.ready().then(() => {
      this.checkToken();
    });
   }

   checkToken() {
       this.storage.get(TOKEN_KEY).then(access => {
           if (access) {
               this.user = this.helper.decodeToken(access);
               this.authenticationState.next(true);
           }
       });
   }

   apilogin(username: string, password: string) {
    return this.http.post<any>(`${this.url}/api/token/`, { username, password })
    .pipe(
        tap(res => {
            this.storage.set(TOKEN_KEY, res['access']);
            this.storage.set(USERNAME_KEY, username);
            this.user = this.helper.decodeToken(res['access']);
            console.log('my user: ', this.user);
            this.authenticationState.next(true);
        }),
        catchError(e => {
            this.showAlert('Oops smth went wrong!');
            throw new Error(e);
        }));
}

And here is the snippet from user.service.ts:

  // get a user's profile
  getUserDetails(id: number): Observable<any> {
    return this.http.get(`${this.url}/users/${id}/`);
  }

Lastly, in profile.ts:

 information = null;
 id: number;


      ngOnInit() {
        // How to get just the authenticated api?
        this.activatedRoute.paramMap.subscribe(params => { 
         this.id = validateId(params.get('id'));
     });

        function validateId(id: any): number {
           return parseInt(id);
    }

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

Answer №1

Latest Update To store the user_id, you can use the following code snippet:

this.storage.set(USER_ID, this.validateId(res['user_id']))

In your current user profile component, retrieve the user_id from storage and pass it to this.userService.getUserDetails method like this:

const currentUserId = this.storage.get(USER_ID); 

this.userService.getUserDetails(currentUserId).subscribe(user => { 
  console.log('user data', user);
});

Prior Solution If all profiles, including the authenticated user, have the same route (e.g., profile/:userId),

You simply need to incorporate this call within the subscription of activatedRoute.paramMap,

like so:

ngOnInit() {
  // How to access only the authenticated user's API?
  this.activatedRoute.paramMap.subscribe(params => { 
    this.id = validateId(params.get('id'));

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

  function validateId(id: any): number {
    return parseInt(id);
  }
}

To clarify, upon entering this component, the ngOnInit hook is triggered to fetch a user by ID. When attempting to view the current authenticated user, only the callback of the activatedRoute.paramMap subscription is executed, not the entire ngOnInit method.

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

Is there a difference between new Date(..).getTime() and moment(..).valueOf() in momentJS?

new Date(..).getTime() is expected to provide a timestamp in milliseconds. In the documentation of momentJS, it states that the expression moment(..).valueOf() should also yield a timestamp in milliseconds for a given date. To verify this claim, I conduct ...

Angular oppositional $watch

Can an inverse use of $watch in Angular be implemented? The Issue I am using angular-translate and I aim to execute a $http.put for every missing translation. However, I encounter the following error: "10 $digest() iterations reached" when ...

What is the best way to implement conditional routing in Angular to ensure that the user has visited the previous page before accessing the current one?

In my Angular web application, the sign-up process involves navigating through multiple pages: Enter your name and email Create a password Provide a confirmation code As a result, the URL transitions from website.com/intake to website.com/intake/signup t ...

What could be causing the child view to not display the AJAX result?

An AJAX call is being made in the following manner: @Ajax.ActionLink("My Schedule", "GetSchedule", "Schedule", new { selectedDate = strToday}, new AjaxOptions { UpdateTargetId = "theTimes", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }) Th ...

The ReactJS code encountered an error when attempting to access the 'location' property of an undefined or null reference

My Reactapp is encountering an error due to a specific file. import React from 'react'; import { Router, Route } from 'react-router'; import App from './components/App'; import About from './components/About'; im ...

An issue has occurred: (SystemJS) XHR error (404 Not Found) while trying to load the resource at http://localhost:3000/ng2-google

I attempted to implement the ng2-google-recaptcha component found at https://github.com/leewinder/ng2-google-recaptcha. I followed the instructions on the page, but encountered the following error: Error: (SystemJS) XHR error (404 Not Found) loading htt ...

Unnecessary Page Diversion

Within my index.php file, I have a download button with the id of "render". Using AJAX, I am sending a request to the server. The JavaScript code being utilized is as follows: $('#render').click(function(e){ $('html,body').animat ...

Exploring the synergies between Typescript unions and primitive data types in

Given the scenario presented interface fooInterface { bar: any; } function(value: fooInterface | string) { value.bar } An issue arises with the message: Property 'bar' does not exist on type '(fooInterface | string)' I seem ...

What is the best way to retain data after clicking a button?

I am facing an issue where I need to figure out how to add information to a new page when a button is clicked. For example, let's say I have an "add to cart" button and upon clicking it, I want to store some data. How can I achieve this functionality? ...

Angular provides a variety of functionality to control the behavior of elements in your application, including the

I have a page with Play, Pause, Resume, and Stop icons. When I click on the Play icon, the Pause and Stop icons are displayed. Similarly, I would like to show the Resume and Stop icons when I click on the Pause icon. I need help with this code. Thank you. ...

What are the steps for incorporating PNotify into a specific div element on a webpage?

I'm currently utilizing the Pnotify plugin to display notifications, but I am encountering an issue where the notifications are only appearing in specific areas of my page. I would like to have them appended to the header class within my page layout, ...

Arranging an Array of Arrays Containing Strings

Looking for a solution to sort an array containing arrays of strings? A similar issue was discussed here. Here is the array in question: var myArray = [ ['blala', 'alfred', '...'], ['jfkdj', ...

What is the best way to find the product of each object in an array by the corresponding values in another array?

Searching for a solution to an issue I encountered while working on an assignment. The problem can be illustrated as follows: var arrOfObj = [{a:10 },{a:20},{a:30}, ......] var arrToMultiply = [2,4,6, .....] The expected result const result = [{a:10,resul ...

What is the best way to extract a specific value from a line of data using JavaScript (JSON)?

My current task involves extracting the "correctAnswers" from a specific number. Let's take a look at this JSON example: { "questions": [ { "number": 3, "question": "☀️ ➕ ...

How can you update the options within a select tag depending on the selected index of another select tag using AngularJS?

Consider the following code snippet: $scope.letters = ['A', 'B', 'C', 'D']; $scope.numbers = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]; $scope.selectedLetter = 0; There are two select tags in t ...

Check if a Firestore document exists and display a button in Angular based on the boolean result

Seeking desired outcome: How to display a button in an Angular view based on the boolean value returned by an Angular Service that checks for the existence of a Firestore document. Current Scenario The Service successfully verifies the presence of t ...

What is the best way to incorporate multiple class names based on varying conditions using ng class in Angular?

I am facing a challenge where I need to add 2 different class names under specific conditions to an element: ng-class="(commentItem.comment | escapeHtml | direction)" The first condition works well, as it retrieves the text content of the given HTML stri ...

Rotating and scaling an image simultaneously using CSS3

I am feeling very puzzled. Why am I unable to simultaneously scale and rotate? Despite my attempts, it seems to be not working: .rotate-img{ -webkit-transform:scale(2,2); -webkit-transform:rotate(90deg); margin-left:20%; margin-top:10%; } ...

The initial value in useEffect is not being updated by useState

I am currently implementing a like feature for my web application. The issue lies in the fact that my setLike function is not updating the state even after using setLike(!like). I verified this by adding console.log() statements before and after the setLik ...

javascript - Transferring content from one div to another document

Managing a small website that includes both mobile and desktop index pages can be quite a task. To streamline the editing process, I am looking for a way to modify one index page while automatically generating the content for the other from it. This will h ...