0

I'm getting this only when I subscribe to the function that makes api call from inside the Angular service, so the object that subscribes to the function is empty. Here's my code snippet from my service:

getSchedules(): Observable<Schedule[]> {    
  this.http.get<TempSchedules[]>(this.apiUrl).subscribe(x => this.temp = x); 

  this.temp.forEach((e, i) => {    
  // Do something, this loop is never executed because this.temp is empty  
  });
  // Some processing here  
    
return something; }

Here is my http.get function somewhere inside the service:

 getTempSchedules(): Observable<TempSchedules[]> {
    return this.http.get<TempSchedules[]>(this.apiUrl);
  }

From the above, this.temp is empty. Why is that?

I called the above function in the service constructor as

  constructor(private http:HttpClient) {     
    this.getTempSchedules().subscribe(x => this.temp = x); 
  }

Here is a code snippet from a component that calls that function in the service:

ngOnInit(): void {
    this.scheduleService.getTempSchedules().subscribe(x => this.tempSchedules = x);  
}

The component works fine, so when I use the value this.tempSchedules in the html it is displayed correctly. What am I missing here?

1
  • Thank you @Drenai, it's different. i already subscribed and i didn't use pipe in my questino Commented May 17, 2022 at 0:56

1 Answer 1

2

It is not working because you are not getting the way observable works. It is async process and you need to be in subscribe block to get it. In case you want to do some funky stuff with the response before returning it to the component, then you should use map

getTempSchedules(): Observable<Schedule[]> {    
   return this.http.get<TempSchedules[]>(this.apiUrl)
   .pipe(map(res => {
      return res.forEach(() => {
           // Do something, this loop will be executed 
      })
    })) }

use it in component as :

ngOnInit(): void {
    this.scheduleService.getTempSchedules().subscribe(x => this.tempSchedules = x);  
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @Shashank. I'm having this dilemma. When looping res.forEach((e) => { var day = dd.getDay(); var {index, length} = this.getSlotNumber(e.startTime.hours, e.startTime.minutes, e.endTime.hours, e.endTime.minutes); this.arr[day].times[index] = length; for (var k = index; k<=length+index-1; k++) { console.log(day + ' cc ' + k) this.arr[day].assigned[k] = true; } when day = 1, the for loop actually assigned true for the assigned array in all the days. where day=0 to 6. Any idea if this is related?
@William No, thats unrelated. Hard to say unless I know more about this loop. May be another que

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.