What is the best way to pass data from an http request to another component. I have programmed a user service here, which receives information about a user. Now I want to retrieve this in my login component. When I output the User Object to the console, console.log(this.user) returns undefined. Why is this and how can I solve the problem?
user.service.ts
@Injectable({ providedIn: 'root' })
export class UserService {
user: User;
constructor(private http: HttpClient) {}
fetchUserByUsername(username: string){
this.http
.get<User>('http://localhost:8080/user/getByUsername?username=' + username)
.subscribe(data => {
this.user = data;
});
return this.user;
}
}
login.component.ts
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers:[UserService]
})
export class LoginComponent {
hide = true;
user: User;
constructor(private userService: UserService) { }
validate() {
this.user = this.userService.fetchUserByUsername('bonguen');
console.log(this.user)
}
}