【问题标题】:How "this" work within a _.each loop? / how do you call on a return from a _.each loop?“这个”如何在 _.each 循环中工作? / 你如何调用 _.each 循环的返回值?
【发布时间】:2018-10-08 10:45:41
【问题描述】:

我正在尝试使用 Angular Material 创建一个模态,但我很难让我的数据显示出来。我得到的错误是它找不到未定义的 listOfPaths。看起来在嵌套的 _.each 循环中添加“this”会产生这个问题。我对正在发生的事情感到困惑,并希望得到指导。

这是我的代码:

在 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>

【问题讨论】:

  • 尝试将您的functions 更改为箭头函数。像这样:(path) =&gt; {...。与具有fileType 参数的函数相同。
  • @R.Richards 当我尝试这样做时,它也没有用。

标签: angular angular-material lodash


【解决方案1】:

在将函数作为回调传递时,您会丢失上下文。而且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 方法,允许将上下文作为第三个参数传递。

【讨论】:

  • 感谢 Yury Tarabanko 的帮助,模式现在可以正确显示了!
猜你喜欢
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 2012-12-24
  • 2022-01-03
  • 1970-01-01
  • 2015-11-12
相关资源
最近更新 更多