更新页面内容

时间:2018-05-18 15:43:31

标签: components refresh

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

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, '$1-$2-$3');
              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)">

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

我建议你使graphData成为一个可观察的,并在你的html中使用异步管道。像这样:

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

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

[graphData]="graphData$ | async"

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

编辑:

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

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

}

答案 2 :(得分:1)

我终于开始工作了。我试图清除morris图表并使用新数据生成图表。因此,每当数据发生变化时,它都会清除图形并用新数据重绘图形。

清除图表

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

这将再次绘制图表

this.generateChart(graphDataArr, data.names, yKeysArr);
相关问题