0

Angular 6 Service

getProjectEpics(id: string): Observable<any> {
return this.http.get<any>(this.baseUrl + 'getEpics/' + id);
}

Component Angualr 6

projectEpics=[];
getProjectEpics(id: string) {
this.epicService.getProjectEpics(this.id).subscribe(
  next => {
    console.log('RESPONSE', next);
    this.projectEpics = next[0].epics;
    console.log(this.projectEpics); // array has data
  },
  error => {
    this.alertify.error(error);
  }
);
console.log(this.projectEpics); // The array is empty at this log.
}

I am using Angularr 6. I have a method returning observable of type any getProjectEpics in serive which is calling an API. Then in my component i am subscribing to observable method avaliable in service. I successfully get the data from the API and serive but issue is that when i assign the data present in next object to my local array projectEpics and log projectEpics array inside next to console, it displays the array but, when i log it outside next or outside subscribe the projectEpics array is empty and shows no data.

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
Muhammad Ali
  • 97
  • 1
  • 9
  • Make your next as (next), and error as (error) and try – Aijaz Mar 14 '19 at 18:04
  • Maybe `console.log(this.projectEpics);` is called before receiving a response from the server (as it is in this snippet)? Http calls are asynchronous. In that case you just don't wait for answer from Http call. – Bardr Mar 14 '19 at 18:06

2 Answers2

1

This is the way it works when using async calls, you only have access to variables in that scope/thread. you could use a service / RxJS subjects / ... to communicate to the outside

jcuypers
  • 1,774
  • 2
  • 14
  • 23
1

Observables are asynchronous in nature. Javascript is a single thread environment and any asynchronous tasks it detects are handed off to enclosing environment(Browser,NodeJS etc.,) to execute it in a separate thread. When javascript tries to run your code, it does the following:

  1. Main thread Call to getProjectEpics()
  2. Checks the statement this.epicService.getProjectEpics() and hands off the execution
  3. Main thread executes your last console.log() - this happens even before the second step is finished

Array is empty in the last console.log() statement as it won't wait for the API call to finish.

For a detailed explanation, please see https://www.youtube.com/watch?v=8aGhZQkoFbQ

ilogs
  • 111
  • 3