Answer the question
In order to leave comments, you need to log in
How to display the data of the current user?
I want to display logged in user details. But instead, I have the data of a completely different user, and not the one who logged in. What needs to be corrected to display the data of the authorized (current) user?
auth.service:
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
export class User {
id?: string;
username?: string;
roles?: string;
name?: string;
password?: string;
createdAt?: string;
photoSrc?: string;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
currentUser: User = new User();
private token = null;
constructor(
private http: HttpClient
) {}
login(user: User): Observable<{token: string}> {
return this.http.post<{token: string}>('/api/auth/login', user)
.pipe(
tap(
({token}) => {
localStorage.setItem('auth-token', token)
this.setToken(token)
this.setCurrentUser()
}
)
)
}
setCurrentUser():User {
return this.currentUser;
}
setToken(token: string) {
this.token = token
}
getToken(): string {
return this.token
}
isAuthenticated(): boolean {
return !!this.token
}
logout() {
this.setToken(null)
localStorage.clear()
}
}
import { Component, OnInit } from '@angular/core';
import { AuthService, User } from '../../services/auth.service';
import { Router } from '@angular/router';
import { UserService } from '../../services/user.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: User;
constructor(
private auth: AuthService,
private router: Router,
private userService: UserService
) {}
ngOnInit() {
this.getUser();
}
getUser() {
this.userService.getById(this.auth.currentUser).subscribe(
data => this.user = data
);
}
}
...
getById(user: User): Observable<User> {
return this.http.get<User>(`/api/user/${user.id}`)
}
...
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question