BishtDev
BishtDev

Reputation: 33

Getting Undefined after subscribe successfully called in angular

I have successfully called the API and data from it however if I read the variable I am getting "Undefined".

Service Class which call api to get data

export class DataServiceService {

   constructor(private http: Http) { }

   url: string = "http://localhost:60263/api/values";

   getEmployeesData(): Observable<EmployeeDetails[]> {
      return this.http.get(this.url).map((res: Response) => res.json());
   }
}

Subscribing data

export class AppComponent {

   emp: EmployeeDetails[];

   constructor(private dataServe: DataServiceService) { }

   ngOnInit() {
     this.dataServe.getEmployeesData().subscribe(res => this.emp = res);
   }

   clEmployeesCount: Number = this.emp.length; **Getting undefined here**
   clShowEmployee: boolean = false;
   clCreateEmployee: boolean = false;
}

however this works fine at HTML part

<div *ngIf="emp">
  <ul *ngFor="let user of emp">
   <li>{{user.ID}}</li>
 </ul>
</div>

Upvotes: 0

Views: 14403

Answers (2)

Franklin Pious
Franklin Pious

Reputation: 3858

this.emp is assigned the value only after

clEmployeesCount: Number = this.emp.length;

Getting undefined here is executed.

Either you could move

clEmployeesCount: Number = this.emp.length; 

inside the subscribe or assign a null array initially

emp: EmployeeDetails[] = [] 

to avoid the error. Moving it into subscribe is the proper method.

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68685

As it is an asynchronous call, you can't know when it will be returned. So move the assignment into the subscribe function

this.dataServe.getEmployeesData().subscribe(res =>  {
   this.emp = res;
   this.clEmployeesCount = emp.length;
});

Upvotes: 6

Related Questions