Get Subscribe Data out of .subscribe in Angular

喜夏-厌秋 提交于 2019-12-24 14:09:51

问题


I want to return the events after the subscriber is called.

 getCalendarData(){
      var body = JSON.stringify({"cid": "etNG3V61LWS6Pzkeb_omuZGMVAOLd1_70tRQblVizWQ~",
      "seldt":"2018-09-18"}); 
      var headers = new HttpHeaders();
      headers.append('Content-Type', 'application/json');

      return this.httpClient.post(this.apiUrl, body, { headers: headers })

    }

The above code works perfectly. It also returns the JSON.

Now the problem is, when I call this method inside the getCalendarEvents(), I failed to return the events as the function is not void. So it should have a return type. So how will I pass events since subscribe is asynchronus.

 getCalendarEvents(): Array<CalendarEvent> {
         var listCal:any = []
         this.getCalendarData().subscribe((data: any) => {
          listCal = data;
              console.log('listCal data: ', listCal);  

             let startDate: Date,
             endDate: Date,
             event: CalendarEvent;
             let colors: Array<Color> = [new Color(200, 188, 26, 214), new Color(220, 255, 109, 130), new Color(255, 55, 45, 255), new Color(199, 17, 227, 10), new Color(255, 255, 54, 3)];
             let events: Array<CalendarEvent> = new Array<CalendarEvent>();
             for (let i = 1; i < listCal.length; i++) {
                  event = new CalendarEvent(listCal[i].title, new Date(listCal[i].date), new Date(listCal[i].date), false, colors[i * 10 % (listCal[i].colour.length - 1)]);    

                  events.push(event);     
              }
             //console.log(events);     
             return events;
           }
         );    

         //return events; HERE the events has no data because I am outside the .subscribe!
    }

回答1:


You will need to treat this like an async function, because it is. Here are two ways:

import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';

getCalendarEvents(): Observable<Array<CalendarEvent>> {
  return this.getCalendarData().pipe(map((data: any) => {
    // Your parsing code...
    return events;
  }));
}

// or:

getCalendarEvents(): Observable<Array<CalendarEvent>> {
  const result: Subject<Array<CalendarEvent>> = new Subject<Array<CalendarEvent>>();
  this.getCalendarData().subscribe((data: any) => {
    // Your parsing code...
    result.next(events);
    result.complete();
  });
  return result;
}


来源:https://stackoverflow.com/questions/54873434/get-subscribe-data-out-of-subscribe-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!