Как обновить angular -плотно. js график при изменении данных в angular 7 - PullRequest
0 голосов
/ 05 февраля 2020

Я занимаюсь разработкой приложения в Angular 8 и отображаю график разброса, используя angular -плотно. js. Для данных в x, y я получаю данные из остальных API. И я могу построить график, используя данные из остальных API. На веб-интерфейсе у меня есть два выпадающих меню, из которых пользователь может выбрать параметр и отправить значение этих параметров в бэкэнд, и в ответ я получаю новые данные обратно в веб-интерфейс. До этого момента все работало нормально, но проблема, с которой я сталкиваюсь, заключается в том, что мой график не обновляется новыми данными. Внешний интерфейс все еще показывает начальный график, а не новый график с другим значением данных.

Мой Html код:

Вот мои два раскрывающихся списка, из которых пользователь выбирает параметры и на основе этих опций от бэкэнда до рестапа я получаю точки данных для построения графика. И когда пользователь меняет любой вариант из выпадающего списка и отправляет новый выбор в бэкэнд, я снова получаю новую точку данных, и мне нужно удалить свой старый график и отобразить новый график на основе нового набора данных.

<form (ngSubmit)="segmentSelection()" #ff="ngForm">
            <div id="userSelection" ngModelGroup="userData" #userData="ngModelGroup">
          <mat-form-field>
            <mat-label>Choose Segment Key</mat-label>
            <mat-select id="selectme" ngModel name="segmentKey">
              <mat-option *ngFor="let segment of segKeys" [value]="segment">
                {{segment}}
              </mat-option>
            </mat-select>
          </mat-form-field>

          <mat-form-field style="margin-left: 30px;">
            <mat-label>Choose Target Variable</mat-label>
            <mat-select id="myselect" ngModel name="target_variable">
              <mat-option *ngFor="let msg of mymessage" [value]="msg">
                {{msg}}
              </mat-option>
            </mat-select>
          </mat-form-field>
          <button type="submit" class="btn btn-success btn-color" (click)="plotDiv()" style="margin-left: 20px;">Submit</button>
        </div>
        </form>

<plotly-plot [data]="graph.data" [layout]="graph.layout"></plotly-plot>

Мой Код component.ts:

myhistoricPlot = []
myhistoricDate = []

segmentSelection(){
  this.plotselection.segmentKey = this.segmentData.value.userData.segmentKey;
  this.plotselection.target_variable = this.segmentData.value.userData.target_variable;
  console.log(this.segmentData);
  fetch("http://localhost:5000/data-decomposition", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },body: JSON.stringify({
      segmentKey: this.segmentData.value.userData.segmentKey,
      target_variable: this.segmentData.value.userData.target_variable
    })
  }).then(res => res.json()
    // console.log(res);
    // console.log('hello saheb')
    // console.log(res.json())

  ).then(myjson => {

    myjson['Data'].forEach(element =>{
      this.myhistoricPlot.push(element)
    })
    myjson['Date'].forEach(element =>{
      this.myhistoricDate.push(element)
    })
    // console.log(this.myhistoricPlot)})
    // this.myhistoricDate = myjson['Date'];
    // this.myhistoricPlot = myjson['Data'];
    console.log(this.myhistoricDate);
    console.log(this.myhistoricPlot);
    console.log(myjson)
    this.myhistoricPlot = [];
    this.myhistoricDate = [];
    })
}

public graph = {
    data: [
        { x: this.myhistoricDate, y: this.myhistoricPlot, type: 'scatter', mode: 'lines+points', marker: {color: 'black'} },

    ],
    layout: {width: 1200, height: 600, title: 'Historical Actuals Plot'}
}; 

**** Примечание: myhistoricDate, myhistoricPlot - это два списка с некоторыми числовыми значениями, в которые я получаю данные из restapi.

Спасибо .... Ваша помощь в этом вопросе будет высоко оценена

1 Ответ

0 голосов
/ 05 февраля 2020

Попробуйте добавить ChangeDetectionStrategy:

import { ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export MyComponent implements OnInit {

constructor(private _cd: ChangeDetectorRef) {}

...
).then(myjson => {

    myjson['Data'].forEach(element =>{
      this.myhistoricPlot.push(element)
    })
    myjson['Date'].forEach(element =>{
      this.myhistoricDate.push(element)
    })
    // console.log(this.myhistoricPlot)})
    // this.myhistoricDate = myjson['Date'];
    // this.myhistoricPlot = myjson['Data'];
    console.log(this.myhistoricDate);
    console.log(this.myhistoricPlot);
    console.log(myjson)

    this._cd.detectChanges();
    ...
    })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...