【问题标题】:How to pass async data to google-charts-angular?如何将异步数据传递给 google-charts-angular?
【发布时间】:2021-01-23 05:48:37
【问题描述】:

我正在尝试根据从 API 调用中获得的数据创建图表。为此,我使用了 google-charts-angular 包。这就是我的 html 的样子:

<google-chart [title]="title" [type]="type" [data]="data"  [options]="options"></google-chart>

我只需要将数据传递给图表。我在我的 component.ts 文件中这样做。首先,我用自己编造的随机数据对其进行了测试:

title = 'Issues';
  type = 'Gantt';
  data = [
    ['1', 'Read', 'whatever', //More data ....],
    ['2', 'Write', 'whatever' // More data ...,
  ];
  columnNames = [
    ['string', 'Task ID'],
    ['string', 'Task Name'],
    ['string', 'Resource'],
    // More colums ...
  ];

这就像它应该的那样工作。现在我想使用 API 中的数据。 GetIssues 使用 http.get() 函数返回一个 Observable:

ngOnInit(): void {
  this.apiService.getIssues().subscribe(response => {})
}

问题是我不知道如何从订阅图表中获取异步数据。我试图将新数组推送到数据数组,但没有奏效:

    issues = [];
    data = [
        ['1', 'Read', 'whatever', new Date(2015, 0, 1), new Date(2015, 0, 3),  1, 100, null],
        ['2', 'Write', 'whatever', new Date(2015, 0, 4), new Date(2015, 0, 7),  1, 100, null],
      ];
          ngOnInit(): void {
            this.apiService.getIssues().subscribe(response => {
              this.issues = response;
              if (this.issues) {
                let id = 3;
                for (let issue of this.issues) {
                  this.data.push([id, issue.title, 'whatever', new Date(2015, 0, 4), new Date(2015, 0, 7),  1, 100, null]);
                  id += 1;
                }
              }
            });
          }

图表将显示数据中的两个组成数组,但不会显示我想通过推送添加的新数组。我认为问题在于图表在订阅完成之前被渲染。如果这真的是问题,我不知道在 asyc 部分完成后如何渲染图表。

【问题讨论】:

    标签: angular typescript rxjs observable


    【解决方案1】:

    自己找到了解决方案:

      ngOnInit(): void {
        this.issues = this.apiService.getIssues();
        this.issues.subscribe(response => {
          this.data.push( ['1', response[0].title, 'whatever', new Date(2015, 0, 4), new Date(2015, 0, 7),  1, 100, null]);
        })
      }
    

    在模板中:

    <div *ngIf="issues | async">
        <google-chart [title]="title" [type]="type" [data]="data" [options]="options"></google-chart>
    </div>
    

    我做的是

    1. Http.get 返回一个 Observable。我将它保存在名为 issues 的变量中
    2. 在我的模板中使用 *ngIf 我检查 issues 是否存在
    3. 在 *ngIf 中,我通过管道传输到 async 以确保它一直等到 Observable 返回了一些东西
    4. 我在 issues 上使用 subscribe 并将我需要的值推送到数据中

    我不知道这是否是一种好方法,是否会带来问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-07
      • 2015-12-01
      相关资源
      最近更新 更多