简体   繁体   中英

API call returns empty object when called from inside Angular service

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?

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);  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM