1

由于我为数组创建并添加了自定义过滤器管道,因此在加载视图时出现此异常:

TesttypesListComponent - inline template:35:14 caused by: Cannot read property '0' of undefined

我猜这一定与我加载数据的方式有关。

在我添加管道数据加载之前!

我可以在管道中放置一个断点,但由于错误,它永远不会被击中。

任何人都知道我的第一个管道做错了什么?

管道

从“@angular/core”导入 { Pipe, PipeTransform };

@Pipe({
    name: 'TestTypePipe'
})
export class TestTypePipe implements PipeTransform {
    transform(testTypes, args?) {
        let [currentSubject, currentSchoolclass] = args;
        if (!currentSubject || !currentSchoolclass) {
            return [];
        }
        else {
            return testTypes.filter(s => {
                return s.subjectId == currentSubject.subjectId && s.schoolclassId == currentSchoolclass.schoolclassId;
            });
        }
    }
}

HTML

  <tbody>
          <tr *ngFor="let t of testTypes | TestTypePipe:currentSubject:currentSchoolclass; let i = index">
            <template [ngTemplateOutlet]="getTemplate(t)" [ngOutletContext]="{ $implicit: t, index: i }"></template>
          </tr>
        </tbody>

零件

  currentSubject: Subject;
  currentSchoolclass: Schoolclass;

      ngOnInit() {
this.route.params.subscribe(params => { this.schoolyearId = parseInt(params['id']); });

        this.testService.getTestTypes(this.schoolyearId).subscribe(data => {
          this.schoolclasses = data.schoolclasses.map(m => new Schoolclass(m));
          this.subjects = data.subjects.map(m => new Subject(m));

          for (let t of data.testTypes) {
            t.viewMode = ViewMode.Displaying;
            let testType = new AssignedTestType(t);
            this.testTypes.push(testType)
          }
        }

); }

4

1 回答 1

2

Pipe#transform接受可选的顶级参数,而不是单个args: [].

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'TestTypePipe'
})
export class TestTypePipe implements PipeTransform {
    transform(testTypes, ...args) {
        let [currentSubject, currentSchoolclass] = args;
        if (!currentSubject || !currentSchoolclass) {
            return [];
        }
        else {
            return testTypes.filter(s => {
                return s.subjectId == currentSubject.subjectId && s.schoolclassId == currentSchoolclass.schoolclassId;
            });
        }
    }
}
于 2016-12-03T00:09:11.070 回答