首页 > 解决方案 > 如何从订阅者内部的外部价值中获取

问题描述

我正在使用 chartjs 和 Angular 7 开发仪表板,我需要显示来自工具提示内对象的一些信息。

在此处输入图像描述

我能够在控制台日志中获取对象,但我不知道如何从允许我在屏幕上显示自定义工具提示的函数内部的订阅者获取值。

这是我的代码。

ngOnInit() {

this.batches.forEach(batch => {
        let batchID = batch.batch_id;
        this.dashboardService.getBatchId(batchID).subscribe(singleBatch => {
          this.batch = singleBatch;
          console.log(this.batch)
          let batchName = this.batch.name //<-- THIS IS MY VARIABLE
          console.log(batchName)
        })
      })
}

Duration = {
    tooltips: {
      // Disable the on-canvas tooltip
      enabled: false,

      custom: function(tooltipModel) {
          // Tooltip Element
          var tooltipEl = document.getElementById('chartjs-tooltip');

          // Create element on first render
          if (!tooltipEl) {
              tooltipEl = document.createElement('div');
              tooltipEl.id = 'chartjs-tooltip';
              tooltipEl.innerHTML = '<table style="background-color: #eee;"></table>';
              document.body.appendChild(tooltipEl);
          }

          function getBody(bodyItem) {
              return bodyItem.lines;
          }

          // Set Text
          if (tooltipModel.body) {
              var titleLines = tooltipModel.title || [];
              var bodyLines = tooltipModel.body.map(getBody);
              innerHtml += '<tbody>';

              bodyLines.forEach(function(body, i) {
                  var span = '<span>' +
                  '<p>Batch: </p>' + //<----HERE IT IS THE PLACE WHERE I WANT TO PUT BATCHNAME
                  '</span>';
                  innerHtml += '<tr><td>' + span + body + '</td></tr>';
              });
              innerHtml += '</tbody>';
          }
      }

  }
};

提前致谢。

标签: angular

解决方案


我将对此进行伪编码,因为我不在我的开发机器上。

从您的代码中,您已经有了批次的变量,例如 this.batches,那么为什么要返回您的服务来获取批次?例如

 this.batches.forEach(batch => { console.log(batch.name) });

您只需要一个函数来显示工具提示,例如

 tooltip(batch: Batch) => { batch.name }

然后你应该从你的html中调用它

<div *ngFor="let batch in batches">
    <div class="tooltip">{{tooltip(batch)}}</div>
</div>

推荐阅读