You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 9中如何获取当前登录用户信息并存储至本地存储

How to Get Current User ID/Profile and Store in LocalStorage for Angular 9

Hey Sajid, let's work through getting your current user ID and profile info stored properly after login. I'll break this down step by step based on your existing code.

First: Check Your Login API Response

The first thing to confirm is what data your backend returns when you call the /token endpoint. Right now you're trying to access resp["access_id"], but if your backend doesn't return that field (it might be named user_id, id, or nested inside a user object), that's why you're not getting the user ID.

  • Open your browser's DevTools → Network tab
  • Submit your login form and look at the POST request to /token
  • Check the Response tab to see the exact JSON structure (e.g., does it include user_id, username, or other user details?)

Scenario 1: Backend Returns User Info with Access Token

If your login API already includes user details like ID and profile in the response, modify your signIn method to extract those values correctly:

Update login.component.ts

signIn(credentials) {
  this.errorFlag = false;
  this.authService.blockUI.start();
  this.authService.login(credentials)
    .subscribe( resp => {
      let returnUrl = this.router.snapshot.queryParamMap.get('returnURL');
      if (resp !== undefined && resp["access_token"]) {
        // Store the access token
        localStorage.setItem(AppConstants.userInfo, resp["access_token"]);
        
        // Extract user info from the response (adjust field names to match your API!)
        const userProfile = {
          id: resp["user_id"], // Replace with your actual field name (e.g., resp.id, resp.user.id)
          username: resp["username"],
          // Add other profile fields as needed
        };
        
        // Store full user profile as JSON (better than individual keys)
        localStorage.setItem(AppConstants.userProfile, JSON.stringify(userProfile));
        // Optional: Store individual fields if you need quick access
        localStorage.setItem("userid", userProfile.id.toString());
        localStorage.setItem("message", `Welcome ${userProfile.username}`);
        
        this.route.navigate([returnUrl || '/']);
      } else {
        this.invalidLogin = true;
      }
      this.authService.blockUI.stop();
    }, (error) => {
      this.authService.blockUI.stop();
      if (error instanceof BadInput) {
        this.errorMessage = error.message;
      } else if (error.status === 400) {
        this.errorMessage = error.error?.error_description || 'Invalid login credentials';
      }
      this.errorFlag = true;
    });
}

Scenario 2: Backend Only Returns Access Token (Need Separate API Call)

If your /token endpoint only returns the access token and no user details, you'll need to call a second API (like /api/user/me) to fetch the user profile using the token.

Step 1: Add a Method to AuthService

Update your auth.service.ts to include a method that fetches the current user:

import { throwError, Observable } from 'rxjs';
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
// ... other imports

@Injectable()
export class AuthService {
  constructor(private http : HttpClient){
    // ... existing constructor code
  }
  // ... existing methods

  // Add this method to fetch current user profile
  getCurrentUser(): Observable<any> {
    const token = localStorage.getItem(AppConstants.userInfo);
    if (!token) {
      return throwError(() => new AppError('No token found'));
    }
    // Set Authorization header with Bearer token
    const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
    return this.http.get(`${environment.apiURL}/user/me`, { headers })
      .pipe(
        catchError(this.ErrorHandler)
      );
  }

  // Fix the ErrorHandler to return proper Observable
  private ErrorHandler(error: HttpErrorResponse): Observable<never> {
    if(error.status === 404) {
      return throwError(() => new NotFoundError());
    }
    if(error.status === 400) {
      return throwError(() => new BadInput(error.error?.error_description || 'Bad Request'));
    }
    return throwError(() => new AppError(error));
  }
}

Step 2: Update Login Component to Call the New Method

Modify the signIn method in login.component.ts to fetch the user profile after login:

signIn(credentials) {
  this.errorFlag = false;
  this.authService.blockUI.start();
  this.authService.login(credentials)
    .subscribe( resp => {
      let returnUrl = this.router.snapshot.queryParamMap.get('returnURL');
      if (resp !== undefined && resp["access_token"]) {
        const token = resp["access_token"];
        localStorage.setItem(AppConstants.userInfo, token);
        
        // Fetch user profile using the token
        this.authService.getCurrentUser().subscribe(user => {
          // Store full user profile
          localStorage.setItem(AppConstants.userProfile, JSON.stringify(user));
          localStorage.setItem("userid", user.id.toString());
          localStorage.setItem("message", `Welcome ${user.username}`);
          
          this.route.navigate([returnUrl || '/']);
        }, (profileError) => {
          // Handle error fetching user profile
          this.errorMessage = 'Failed to fetch user profile';
          this.errorFlag = true;
          this.authService.blockUI.stop();
        });
        
      } else {
        this.invalidLogin = true;
        this.authService.blockUI.stop();
      }
    }, (error) => {
      this.authService.blockUI.stop();
      if (error instanceof BadInput) {
        this.errorMessage = error.message;
      } else if (error.status === 400) {
        this.errorMessage = error.error?.error_description || 'Invalid login credentials';
      }
      this.errorFlag = true;
    });
}

Optimize Access to Current User

Update the currentUser method in AuthService to return the parsed user profile instead of just the token:

currentUser(): any {
  const userProfileStr = localStorage.getItem(AppConstants.userProfile);
  return userProfileStr ? JSON.parse(userProfileStr) : null;
}

Now you can easily get the current user ID anywhere in your app:

const currentUser = this.authService.currentUser();
if (currentUser) {
  console.log('Current User ID:', currentUser.id);
}

Key Notes

  • Always use JSON.stringify and JSON.parse when storing objects in LocalStorage (since it only supports strings)
  • Make sure your backend's /user/me endpoint is secured and requires a valid Bearer token
  • Handle errors properly for both login and profile fetch requests

内容的提问来源于stack exchange,提问作者sajid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:27:36