Im currently trying to show the data of an employee after he loggin to his account, i can get the data of the employee from the backend by his username and i can console logged it , but when i assign the data to another variable of type any i console log that variable and i got undefined as a result.
my service file :
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Employee } from '../Employee';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
private apiServerUrl = environment.apiBaseUrl;
constructor(private http: HttpClient) { }
getEmployee(username: String): Observable<any> {
return this.http.get<any>(`${this.apiServerUrl}/getbyuser/${username}`);
}
}
employee.component.ts file
import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { EmployeeService } from '../services/employee.service';
@Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
constructor(public auth: AuthService,private api: EmployeeService) { }
employeeObj : any;
ngOnInit(): void {
let username = localStorage.getItem('username');
if(username != null) {
this.getEmployee(username);
console.log(this.employeeObj); // it shows undefined
}
}
getEmployee(username: String) {
this.api.getEmployee(username).subscribe(
(data) => {
this.employeeObj = data;
console.log(this.employeeObj); // it shows the informations i received from my backend
}, (error: HttpErrorResponse) => {
console.log(error);
}
)
}
}
the result :
CodePudding user response:
This is due to the asynchronous execution of the code which causes the variable to be logged before the value has actually been assigned. There could be multiple solutions to this problem, but it depends on what you actually want to do with your code.
If you are only using data from employeeObj
in the HTML after pulling it, then you could simply just check if the value is undefined and it will automatically updated when the data finishes populating.
You also could just do anything you need to do with your employeeObj
inside of your getEmployee
function.
Otherwise you can make use of promises and async/await
ngOnInit(): void {
let username = localStorage.getItem('username');
if(username != null) {
this.getEmployee(username);
console.log(this.employeeObj);
}
}
async getEmployee(username: String) {
this.employeeObj = await this.api.getEmployee(username).toPromise()
.catch((error: HttpErrorResponse) => {
console.log(error);
});
}