怎么"这"在_.each循环中工作? /你怎么调用_.each循环返回?

时间:2018-04-27 14:47:32

标签: angular angular-material lodash

我正在尝试使用Angular Material创建一个模态,而我很难将数据显示出来。我得到的错误是它找不到undefined的listOfPaths。它看起来像添加"这个"在嵌套的_.each循环中创建了这个问题。我对正在发生的事情感到困惑,并希望获得指导。

这是我的代码:

在data.component.ts

Proxy Error

The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET /staticlayouts/blah.html.

Reason: DNS lookup failure for: localhost:8080staticlayouts

Additionally, a 502 Bad Gateway error was encountered while trying to use an ErrorDocument to handle the request.

在view.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.html

    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);
      });
  });

  }

}

1 个答案:

答案 0 :(得分:0)

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