Как это работает в цикле _.each? / как вы вызываете возврат из цикла _.each? - PullRequest
0 голосов
/ 27 апреля 2018

Я пытаюсь создать модал, используя Angular Material, и мне трудно получить данные для отображения. Ошибка, которую я получаю, состоит в том, что она не может найти listOfPaths из undefined. Похоже, что добавление «this» во вложенный цикл _.each создало эту проблему. Я запутался в происходящем и хотел бы руководства.

вот мой код:

в data.component.ts

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

  @Input() data;

  listOfPaths = [];

  private resourcesLoaded: boolean;

  constructor(private router: Router,
              public dialog: MatDialog) { }

  ngOnInit() {}

  openDialog(): void {
    const dialogRef = this.dialog.open(ViewComponent, {
      width: '1650px',
      data: this.data

    });

  }
}

в view.component.ts

    import { Component, Inject, OnInit } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import * as _ from 'lodash';

@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
})

export class ViewComponent implements OnInit {

  listOfPaths = [];

  constructor(
    public dialogRef: MatDialogRef<ViewComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) {
      this.getPathsAsList();
    }

    ngOnInit() {
    }

  onNoClick(): void {
    this.dialogRef.close();
  }

  getPathsAsList() {

    this.listOfPaths= [];

  _.each(this.data.network, function(path){
    _.each(path.fileTypes, function(fileType){
       this.listOfPaths.concat(fileType.modifiedPaths);
      });
  });

  }

}

в view.component.html

    <ol>
    <ng-container *ngFor="let path of listOfPaths">
      <li>
        <p>{{path}}</p>
    </li>
    </ng-container>
  </ol>

1 Ответ

0 голосов
/ 28 апреля 2018

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

Вам нужно либо поменять обе функции на функции стрелок.

  _.each(this.data.network, (path) => {
    _.each(path.fileTypes, (fileType) => {
       this.listOfPaths = this.listOfPath.concat(fileType.modifiedPaths);
      });
  });

Или захватить массив в замыкании

var listOfPaths = this.listOfPaths = [];

_.each(this.data.network, function(path){
    _.each(path.fileTypes, function(fileType){
       listOfPaths.push.apply(listOfPaths, fileType.modifiedPaths);
      });
  });

Кроме того, вам не нужен lodash для этого. Массивы имеют метод forEach, который позволяет передавать контекст в качестве третьего аргумента.

...