javascript - 无法使用自定义过滤器管道读取未定义的属性 '0'

标签 javascript angular rxjs angular2-observables

因为我已经为数组创建并添加了自定义过滤器管道,所以在加载 View 时出现此异常:

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

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

在我添加之前,管道数据加载成功了!

我可以在管道中放置一个断点,但它永远不会因为错误而在内部命中。

有人知道我的第一个 pipe 哪里做错了吗?

管道

从 '@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)
          }
        }

);

最佳答案

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

关于javascript - 无法使用自定义过滤器管道读取未定义的属性 '0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40942555/

相关文章:

rxjs - 从 observable 中获取第一个和最后一个发出的值

javascript - modal 不想通过 $location AngularJS 打开自己

javascript - localStorage 不保存数据

javascript - 在带有 jade 模板的 Express.js 中使用公开的对象作为值或助手?

javascript - Node JS request.post 在 AWS Lambda 中未触发

Angular Material v6 Mat-Footer - "Cannot read property ' template' of undefined"

http - 缺少可观察方法 RxJS 5.0.0-beta.0

rxjs 轮询定时器数据并在手动刷新时重置定时器

angular - 如何调整 Ionic 4 中的选项卡大小?

javascript - Angular 6 路由重定向未正确重定向