0

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>
BishtDev
  • 33
  • 1
  • 1
  • 8
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – Amit Chigadani Mar 23 '18 at 07:16

2 Answers2

5

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;
});
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • This seems to be the correct answer. I wonder why it has been downvoted. – FAISAL Mar 23 '18 at 07:18
  • This solved the issue, However I was wondering if there is any option for Synchronous call for this. – BishtDev Mar 23 '18 at 09:07
  • @jinnybat Sorry, but no. It is considered and must be asynchronously – Suren Srapyan Mar 23 '18 at 09:11
  • Thanks @SurenSrapyan for the information. However I came across a very strange problem with Post request to a Web API method. application/json content-type request is not even reaching to the web api method however if i change content-type to application/x-www-form-urlencoded this calls the Web API method. I have tried every possible solutions like cors,allow cross origin nothing works in this case. – BishtDev Mar 24 '18 at 18:21
  • I finally figured out the problem. It was related to Cors which was not correctly configured. – BishtDev Mar 25 '18 at 10:11
0

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.

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Franklin Pious
  • 3,670
  • 3
  • 26
  • 30