【问题标题】:How to access data returning from an API Subscribe method outside in Angular如何在 Angular 外部访问从 API 订阅方法返回的数据
【发布时间】:2020-08-06 16:49:09
【问题描述】:

这是我的 Angular 代码块。

demandCurveInfo = [];

ngOnInit() {
    this.zone.runOutsideAngular(() => {
      Promise.all([
        import('@amcharts/amcharts4/core'),
        import('@amcharts/amcharts4/charts'),
        import('@amcharts/amcharts4/themes/animated'),
        import('@amcharts/amcharts4/maps'),
        import('@amcharts/amcharts4-geodata/worldLow'),
      ])
        .then(modules => {
          this.createDemandCurve(modules);

        })
        .catch(e => {
          console.error('Error when creating chart', e);
        });
    });

  }

这是我尝试获取 API 数据的地方。

async getDemandCurveInfo(statusType: string, valueType ) {
    const params = [];
    params.push({code: 'StreamCode', name: 'TG_PS'});
    params.push({code: 'segmentCodes', name: ['US']});
    params.push({code: 'checkinFrom', name: '2019-01-01'});
    params.push({code: 'checkinTo', name: '2019-12-31'});
    params.push({code: 'statusType', name: statusType});
    params.push({code: 'valueType', name: valueType});
    return await this.dashboardServiceHandler.getSegmentDemand([], params).toPromise();

  }

在这个函数中我调用了上面的方法。

 createDemandCurve(modules: any) {
        const am4core = modules[0];
        const am4charts = modules[1];
        const am4themesAnimated = modules[2].default;
        this.getDemandCurveInfo('REAL', 'TTV').then((data) => {
          this.demandCurveInfo.push(data.valueOf().data);
           console.log(this.demandCurveInfo[0]);         <- first
        });

         console.log(this.demandCurveInfo[0]);  <- second

    }

在这里,我试图在外面获取 this.demandCurveInfo[0] 数据。但是我的第二个 console.log 给出了 undefined 之类的输出。第一个 console.log 给出了这样的输出。 我怎么能得到外面的console.log数据?

【问题讨论】:

    标签: arrays angular typescript amcharts4


    【解决方案1】:

    你可以引入一种新方法来做到这一点

    this.getDemandCurveInfo('REAL', 'TTV').then((data) => {
          this.demandCurveInfo.push(data.valueOf().data);
          printData(this.demandCurveInfo[0]);
    });
    
    printData(data: string){
        console.log(data);
    }
    

    【讨论】:

    • 我想在 createDemandCurve(modules: any) 函数中访问这些数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2016-07-20
    • 2018-05-25
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多