I have below code
import { Employee } from '../employee';
import { EmployeeService } from '../employee.service';
export class EmployeeComponent implements OnInit {
employees: Employee[] = [];
constructor(private employeeService: EmployeeService) {}
this.employeeService.getEmployees().subscribe((employees: Employee[]) => {
this.employees = employees;
console.log("Inside " this.employees.length);
});
console.log("Outside " this.employees.length);
}
I am getting all employees via API. I am able to get employee total records inside subscribe
but outside I am not able to get it.
How to achieve it?
CodePudding user response:
Subscribe is async function and it returns value once it's resolves. So in the above code javascript synchronously goes to Outside console log variable and accesses the variable which has no data, then after resolution it goes to Inside console.log variable. Once it has saved data you can access that variable.
You can use async/await to achieve the above code.
CodePudding user response:
Don't know the exact purpose for this but you can use Observables also use Async pipe if you are displaying data.
TS File
import { Employee } from '../employee';
import { EmployeeService } from '../employee.service';
export class EmployeeComponent implements OnInit {
employees: Observable<Employee[]>;
.....
this.employees = this.employeeService.getEmployees()
}
HTML File
// Use 'employees | async' pipe
// Find Length '(employees | async).length'