Передача ключей в объект и использование его в * ngFor - PullRequest
1 голос
/ 14 января 2020

У меня есть ответ API [{"pass":15,"fail":80,"skip":5,"total":100}], и я хочу показать индикатор хода выполнения значений пропуска, сбоя и пропуска. Это должно быть 3 бара.

HTML

<div *ngFor="let summary of summaries" class="result-progress">
    <label for="">{{summary.label}}</label>
    <mat-progress-bar class="" [color]="summary.color"  [value]="summary.value"></mat-progress-bar>
    <span class="bar-tooltip" [ngStyle]="{'color': 'black'}">{{summary.value}}</span>
</div>

component.ts

   this.httpService.getResultProgress().subscribe((data) => {

      const res = data[0];
      const summaries = [];
      Object.keys(res).forEach((key)=>{
        summaries.push( {
          "label": key,
          "value": res[key],
          "color": "primary"

        })
        return summaries;
      })

      // chart.data = arr;
      console.log(summaries)

    }, (err) => {
      console.log(err);
    });

вот результат console.log (итоги):

[{…}, {…}, {…}, {…}]
0: {label: "pass", value: 15, color: "primary"}
1: {label: "fail", value: 80, color: "primary"}
2: {label: "skip", value: 5, color: "primary"}
3: {label: "total", value: 100, color: "primary"}
length: 4
__proto__: Array(0)

Я не получаю никакой ошибки. В шаблоне html ничего не идет. Не знаю, что не так.

ожидаемый результат.
enter image description here

Ответы [ 4 ]

2 голосов
/ 14 января 2020

Это потому, что summaries является локальной переменной, определенной в subscribe. Вы должны сделать это членом класса.

export class MyComponent {
   summaries = []; // move it to the top

   ....
   this.httpService.getResultProgress().subscribe((data) => {

      const res = data[0];
      this.summaries = Object.keys(res).map(key=>{
        return {
          "label": key,
          "value": res[key],
          "color": "primary"

        };
      });
}
0 голосов
/ 14 января 2020

HTML добавить asyn c pipe:

<div *ngFor="let summary of summaries | async" class="result-progress">
  <label for="">{{summary.label}}</label>
  <mat-progress-bar class="" [color]="summary.color"  [value]="summary.value"></mat-progress-bar>
  <span class="bar-tooltip" [ngStyle]="{'color': 'black'}">{{summary.value}}</span>
</div>

.ts map с rx js response

import { Component, OnInit } from '@angular/core';
import { HttpService } from './http.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  summaries: Observable<Array<any>>;
  constructor(
    private httpService: HttpService
  ) { }

  ngOnInit() {
    this.summaries = this.httpService.getResultProgress().pipe(
      map(data => {
        const res = data[0];
        return Object.keys(res).map(key => {
          return {
            "label": key,
            "value": res[key],
            "color": "primary"
          };
        });
      })
    );
  }
}
0 голосов
/ 14 января 2020

Определите summaries сверху (в конструкторе) как

this.summaries = []

и в вызове http

this.summaries.push( {
          "label": key,
          "value": res[key],
          "color": "primary"

        }) 
0 голосов
/ 14 января 2020

Похоже, вы не храните сводки в компоненте. Не храните результат изменения данных в const внутри подписки, а храните его в элементе компонента, подобном следующему:

//In the class members
summaries = [];

this.httpService.getResultProgress().subscribe((data) => {

  const res = data[0];
  this.summaries = [];
  Object.keys(res).forEach((key) => {
    this.summaries.push( {
      "label": key,
      "value": res[key],
      "color": "primary"
    })
  });

  // chart.data = arr;
  console.log(summaries);

}, (err) => {
  console.log(err);
});

Также, возвращая что-то в обратном вызове forEach бесполезен, поэтому я удалил return summaries;

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