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 :