angulartypescripthttpnativescriptangular-http

Get Subscribe Data out of .subscribe in Angular


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!
    }

Solution

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