更新页面内容

update page content

我有一个比较不同学生统计数据的莫里斯图。我还有一个模式,我可以在其中添加一个新学生,图表应该会随着新学生的统计数据而更新。添加后,图表正在更新,但只有在我刷新整个页面时才会更新。我如何在不刷新的情况下更新页面?

component.ts

  ngOnInit() {
    this.getData();
  }
getData() {
        this.http.get('url')
          .subscribe(data => {

            const graphData = data.stathistory;
            const graphDataArr = [];
            let currentChar = 'a';

            for (const graphdata in graphData) {
              const curDate = graphdata.replace(/(\d{4})(\d{2})(\d{2})/g, '--');
              const graphdataObj = { 'y': curDate };

              for (const element in graphData[graphdata]) {
                graphdataObj[currentChar] = Number(graphData[graphdata][element].rank);
                currentChar = this.nextChar(currentChar);
              }

              graphDataArr.push(graphdataObj)
              currentChar = 'a';
            }

            const yKeysArr = [];

            for (let i = 0; i < data.domains.length; i++) {
              yKeysArr.push(currentChar);
              currentChar = this.nextChar(currentChar);
            }
            this.generateChart(graphDataArr, data.names, yKeysArr);
          });
      }

      generateChart(graphRanks = [], names = [], yKeys = []) {

        this.graphData = graphRanks;
        this.graphOptions = {
          xkey: 'y',
          ykeys: yKeys,
          labels: names,
          resize: true,
          parseTime: false,
          pointSize: 0,
        };

      }


addStudent(name) {
    this.http.post('url', {
      name: name,
    })
      .subscribe(response => {
          this.getData();
      }
      );
  }

html

    <div *ngIf = 'graphData'  mk-morris-js [options]="graphOptions" [data]="graphData" type="Line" style="height: 500px; width: 100%;">

**code for modal dialog**

    <button type="button" class="btn btn-primary" (click)="addStudent(name)">

如果需要更多信息,请告诉我。

这看起来不错。我建议你添加 console.log(graphRanks);就在 this.graphData = graphRanks 之前;以确保在预期时加载新数据。顺便说一句,您的按钮调用函数 addDomain(name),而在您的脚本中函数名称是 addStudent(name)

我建议您使 graphData 成为可观察对象并在 html 中使用异步管道。像这样:

graphData$ = this.http.get('url').pipe(
    map(x => // do stuff with x here)
)

然后,在您的 html 中,您可以:

[graphData]="graphData$ | async"

这是 Todd Motto 关于 ng-if 的一篇很好的 post: https://toddmotto.com/angular-ngif-async-pipe

编辑:

如果您不想让您的 graphData 成为可观察对象 - 您可以在 addStudent 函数中使用 switchMap。

addStudent(name) {
this.http.post('url', {
  name: name,
})
  .pipe(
      switchMap(x => this.getData())
  }
  );

}

我终于让它工作了。我试图清除莫里斯图表并生成包含新数据的图表。因此,只要有数据更改,它就会清除图形并使用新数据重新绘制图形。

正在清除图表

document.getElementById('idofthegraph').innerHTML = '';

这将再次绘制图表

this.generateChart(graphDataArr, data.names, yKeysArr);