0

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?

Mike
  • 13
  • 9
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – derpirscher Mar 07 '22 at 11:53
  • Hi @derpirscher My question is specific to angular typescript & subscribe method. The link you provided is mostly for JS. – Mike Mar 07 '22 at 12:09
  • There is nothing specific to angular or the `subscribe` method when it comes to getting data from an asynchronous call ... – derpirscher Mar 07 '22 at 12:23
  • 1
    You don't. Why would you need to? – Clashsoft Mar 07 '22 at 12:59
  • Really, sure you don't need it. what are you try to do? – Eliseo Mar 07 '22 at 16:20
  • I am still stuck in this one. Can someone give proper solution or guidance in Angular, Typescript please – Mike Mar 11 '22 at 04:04

2 Answers2

0

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.

prograk
  • 559
  • 4
  • 14
-1

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'

  • Thanks. But I need length in TS file because on basis of that output I need to do some operations. – Mike Mar 08 '22 at 06:53