Ошибка угловой функции у подписчика - PullRequest
0 голосов
/ 11 июля 2019

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

Так что мне нужно получить некоторые данные из моей базы данных (с помощью API), чтобы сделать мои строки.

Во-первых, я получаю семейства с помощью функции getAllFamilles (), во-вторых, я получаю все движки с помощью функции getAffecterServiceFamille () и помещаю их в массив, и в-третьих, я смотрю, влияют ли они на них или нет Функция getOperationsServiceFamille. Если на человека влияет двигатель, мне нужно изменить строку в моем массиве.

Я могу восстановить семейства и движки, но когда я пытаюсь нарисовать свои линии в HTML, рисуется только одна линия.

Пожалуйста, кто-нибудь может мне помочь.

Это мой код компонента:

import {Component, OnInit
} from '@angular/core';
import * as d3 from 'd3';
import {FamillesService} from '../services/familles.service';
import {ActivatedRoute, Router} from '@angular/router';
import {AffaireService} from '../services/affaire.service';
import {AffecterService} from '../services/affecter.service';
import {VarianteService} from '../services/variante.service';
import {OperationsService} from '../services/operations.service';

@Component({
  selector: 'app-encours',
  templateUrl: './encours.component.html',
  styleUrls: ['./encours.component.css']
})
export class EncoursComponent implements OnInit {

  //Variables du controleur
  public listeFamilles: any;
  public listeAffecter: any;
  public listeOperations : any;
  public familles: any = Array<String>();
  public points: any = Array<Object>();
  public operation : any = Array<Object>();
  public test: any;

  constructor(private serviceFam: FamillesService, private serviceOpe: OperationsService, private serviceVar: VarianteService, private serviceAff: AffaireService, private serviceAffecter: AffecterService, private router: Router, private route: ActivatedRoute) {
    this.getFamilles();
  }

  ngOnInit(): void {

    //Tableau qui contient les variables points (pour chaque famille)
    this.familles = [];

    //On parcours les familles
    this.serviceFam.getAllFamilles().subscribe(data => {
      this.familles = data;
      for (let f of this.familles) {

        //Pour chaque famille, on recup les affaires affecter dans ce service
        this.serviceAffecter.getAffecterServiceFamille(3,f.nom).subscribe(data => {
          this.listeAffecter = data;
          for (let a of this.listeAffecter) {

            var pos = this.points.map(function(e) { return e.affaire; }).indexOf(a.id);
            //On complète le tableau contenant les points
            this.points.push({"value": this.getTAT(a.dateEntree), "name": a.affaire.accessoire.nom + " " +
                a.affaire.variante.famille.nom + " " + a.affaire.variante.nom + " " + a.affaire.sn,
              "operateur": "PERSONNE", "affaire":a.id
            });
          }

          this.serviceOpe.getOperationsServiceFamille(3,f.nom).subscribe(data => {
            this.listeOperations = data;
            console.log("test");
          })

          this.draw("#" + f.nom, this.points, {dateDimension: false, color: "teal", labelFormat: "%Y"});
          //On réinitialise le tableau contenant les points
          this.points.length = 0;
          this.operation.length = 0;

        })

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


}

А это мой HTML:

<table *ngIf="listeFamilles">
  <tbody>
    <tr *ngFor="let f of listeFamilles">
      <th style="vertical-align: middle; padding-left: 10px;">{{ f.nom }}</th>
      <td  id="{{f.nom}}"  style="vertical-align: top;"></td>
    </tr>
  </tbody>
</table>

1 Ответ

0 голосов
/ 11 июля 2019

вы используете анти-шаблон "вложенная подписка", вам нужно правильно использовать наблюдаемые более высокого порядка при работе с несколькими наблюдаемыми:

  this.serviceFam.getAllFamilles().pipe(
    switchmap(familles => // switchMap to switch into new observable
      forkJoin( // forkJoin to run observables in parrallel
        // map families to observables and run these calls in parallel
        familles.map(f => forkJoin(
            this.serviceAffecter.getAffecterServiceFamille(3,f.nom),
            this.serviceOpe.getOperationsServiceFamille(3,f.nom)
          ).pipe( // gather them all up
            map(([listAffectere, listeOperations]) => [f, listAffectere, listeOperations])
          )
        )
        // if these are a lot of calls, you can use concat / reduce operator instead to run sequentially
      )
    )
  ).subscribe((data: [familles, listeAffecter, listeOperations][]) => {
    //  now that your observables are done, do the rest.
    this.familles = data.map(d => d[0]);

    for (let d of data) {
      const f = d[0];
      // why are these overwritten at every loop?
      this.listeAffecter = d[1];
      this.listeOperations = d[2];
      for (let a of this.listeAffecter) {
        // this appears unused?
        var pos = this.points.map(function(e) { return e.affaire; }).indexOf(a.id);
        this.points.push({
          "value": this.getTAT(a.dateEntree), 
          "name": a.affaire.accessoire.nom + " " + a.affaire.variante.famille.nom + 
                    " " + a.affaire.variante.nom + " " + a.affaire.sn,
          "operateur": "PERSONNE", 
          "affaire":a.id
        });
      }

      this.draw("#" + f.nom, this.points, {dateDimension: false, color: "teal", labelFormat: "%Y"});
      this.points.length = 0;
      this.operation.length = 0;
    }
  }, 
  err => {
    console.log(err);
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...