在Angular中从.subscribe中获取订阅数据 [英] Get Subscribe Data out of .subscribe in Angular

查看:712
本文介绍了在Angular中从.subscribe中获取订阅数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在订阅者被调用后返回事件.

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

    }

上面的代码可以完美地工作.它还返回JSON.

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

现在的问题是,当我在getCalendarEvents()中调用此方法时,由于函数不无效,我无法返回事件.因此,它应该具有返回类型.那么既然订阅是异步的,那么我将如何传递事件.

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

推荐答案

您将需要像对待async函数一样对待它,因为确实如此.这有两种方法:

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

这篇关于在Angular中从.subscribe中获取订阅数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆