添加路由后应用程序出错

app is giving error after adding routing

该应用程序出现以下错误。它在 filter.pipe.ts

中找不到 value 属性

我已经提供了所有的值,但它似乎仍然不起作用。我无法准确指出导致此错误的原因

ListComponent.html:11 ERROR TypeError: Cannot read property 'length' of undefined
    at FilterPipe.webpackJsonp.../../../../../src/app/filter.pipe.ts.FilterPipe.transform (filter.pipe.ts:12)
    at Object.eval [as updateDirectives] (ListComponent.html:16)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13093)
    at checkAndUpdateView (core.es5.js:12270)
    at callViewAction (core.es5.js:12638)
    at execComponentViewsAction (core.es5.js:12570)
    at checkAndUpdateView (core.es5.js:12276)
    at callViewAction (core.es5.js:12638)
    at execEmbeddedViewsAction (core.es5.js:12596)
    at checkAndUpdateView (core.es5.js:12271)

(filter.pipe.ts:12)>>>>>>
 if (value.length === 0 || !filterString || !propName) {

(List.component.html:16)>>>>>>>
 <li class="list-group-item" *ngFor="let person of personsList | filter:coursestat:'chosenCourse'">

//registration.component.ts

import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { DropDownService } from '../services/drop-down.service';
import { IPersonModel } from '../interface/person-model';
import { InputDataService } from '../services/input-data.service';
// FormBuilder imported from anuglar/forms
import { FormGroup, FormBuilder, Validators } from '@angular/forms';


@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css'],
  providers: [DropDownService, InputDataService]
})
export class RegistrationComponent implements OnInit {

  courseForm: FormGroup;
  personDetail: IPersonModel;
  dropDownArr = [];
  selectedOption = null;
  personsList: IPersonModel[] = [];
  courseStat = '';


  constructor(public dropdown: DropDownService, public fieldData: InputDataService, private fb: FormBuilder) {
  }
  onSubmit(): void {
    // adds the user submited data to personDetail object
    this.personDetail.chosenCourse = this.selectedOption;
    this.personDetail.name = this.courseForm.value.username;
    this.personDetail.email = this.courseForm.value.email;
    this.personDetail.address = this.courseForm.value.address;
    this.personDetail.date = this.courseForm.value.date;
    this.fieldData.setPersonData({ ...this.personDetail });
    this.personsList.push({ ...this.personDetail });
    console.log({ ...this.personDetail });
    this.courseForm.reset();
    console.log(this.personsList);
    console.log(this.courseForm);
  }


  // resets the form on clicking the reset button
  resetForm(): void {
    this.courseForm.reset();
  }
  // sets the dropdownlist values on intialization
  ngOnInit() {
    // form controls validation specicified in the class for the Reactive Forms
    this.courseForm = this.fb.group({
      username: [null, [Validators.required, Validators.pattern(/^[a-z0-9_-]{3,16}$/)]],
      email: [null, [Validators.required, Validators.pattern('([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_.-]+)\.([a-zA-Z]{2,5})')]],
      address: [null, [Validators.required, Validators.minLength(10), Validators.maxLength(100)]],
      date: [null, [Validators.required]],
      select: [null, [Validators.required]]
    });
    this.dropDownArr = this.dropdown.getData();
    // this.personDetail = {
    //   name: '',
    //   email: '',
    //   address: '',
    //   chosenCourse: ''
    // };
    this.personDetail = this.fieldData.getPersonData();
    console.log(this.courseForm);
  }
}

// registration.component.html

<!-- Form with three inputs and one dropdown which intializes with data from service on intialization and validates with min and maxlength-->
<section class="container">
  <!-- ngSubmit calls the function onSubmit on submitting the form  -->
  <form class="form-horizontal" (ngSubmit)='onSubmit()' [formGroup]='courseForm'>
    <div class="form-group">
      <label for="inputUsername" class="col-sm-2 control-label">Username</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="inputUsername" placeholder="Username" formControlName="username" name="name"
          [ngClass]="{inValid: !courseForm.get('username').valid && courseForm.get('username').touched, valid: courseForm.get('username').valid && courseForm.get('username').touched}">
        <span class="help-block" *ngIf="!courseForm.get('username').valid && courseForm.get('username').touched">Please enter a valid username</span>
      </div>
    </div>
    <!-- username input ends here -->
    <div class="form-group">
      <label for="inputEmail" class="col-sm-2 control-label">Email</label>
      <div class="col-sm-10">
        <!-- CSS class applied based on validation -->
        <input type="email" class="form-control" id="inputEmail" placeholder="Email" formControlName="email" name="email" [ngClass]="{inValid: !courseForm.get('email').valid && courseForm.get('email').touched, valid: courseForm.get('email').valid && courseForm.get('email').touched}">
        <span class="help-block" *ngIf="!courseForm.get('email').valid && courseForm.get('email').touched">Please Enter a valid email</span>
      </div>
    </div>
    <!-- email input ends here -->
    <div class="form-group">
      <label for="inputAddress" class="col-sm-2 control-label">Address</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="inputAddress" placeholder="Your Address" formControlName="address" name="address"
          [ngClass]="{inValid: !courseForm.get('address').valid && courseForm.get('address').touched, valid: courseForm.get('address').valid && courseForm.get('address').touched}">
        <!--Display error message on MinLength and MaxLength Validation-->
        <span class="help-block" *ngIf="courseForm.get('address')?.errors?.required && courseForm.get('address').touched">Please Enter Your Address</span>
        <span class="help-block" *ngIf="(courseForm.get('address')?.errors?.minlength?.requiredLength !== courseForm.get('address')?.errors?.minlength?.actualLength) && courseForm.get('address')?.touched">Address should be at least 10 characters long</span>
      </div>
    </div>
    <!-- address input ends here -->
    <div class="form-group">
      <label for="inputDate" class="col-sm-2 control-label">DOB</label>
      <div class="col-sm-10">
        <input type="date" class="form-control" id="inputDate" placeholder="DOB" formControlName="date" name="date" [ngClass]="{inValid: !courseForm.get('date').valid && courseForm.get('date').touched, valid: courseForm.get('date').valid && courseForm.get('date').touched}">
        <!--Display error message on MinLength and MaxLength Validation-->
        <span class="help-block" *ngIf="courseForm.get('date')?.errors?.required && courseForm.get('date').touched">Please Enter a valid Date-of-Birth</span>
        <!-- <span class="help-block" *ngIf="(courseForm.get('date')?.errors?.minlength?.requiredLength !== courseForm.get('date')?.errors?.minlength?.actualLength) && courseForm.get('date')?.touched">Please enter a valid DOB</span> -->
      </div>
    </div>
    <!-- date input ends here -->
    <div class="form-group">
      <label for="sel1" class="col-sm-2 control-label">Choose Course</label>
      <div class="col-sm-10">
        <select class="form-control" id="sel1" formControlName="select" [(ngModel)]="selectedOption" name="select" [ngClass]="{inValid: !courseForm.get('select').valid && courseForm.get('select').touched, valid: courseForm.get('select').valid && courseForm.get('select').touched}">
          <option [value]="selectedOption" [disabled]="true">Choose Your Course</option>
          <option *ngFor="let data of dropDownArr; index as i"  [ngValue]="data.course">{{data.course}}</option>          
        </select>
        <span class="help-block" *ngIf="!courseForm.get('select').valid && courseForm.get('select').touched">Please choose a Course</span>
      </div>
    </div>
    <!-- select input ends here -->
    <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-default" [disabled]=!courseForm.valid>Submit</button>
        <button type="button" class="btn btn-default" (click)="resetForm(f)">Reset</button>
      </div>
    </div>
    <!-- submit and reset buttons ends here -->
  </form>
  <!-- form ends here -->
</section>
<app-list [coursestat]="courseStat" [personsList]="personsList"></app-list>

// list.component.ts

import { Component, OnInit, Input } from '@angular/core';

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

  @Input() coursestat: string;
  @Input() personsList;
  constructor() { }

  ngOnInit() {
  }

}

// list.component.html

<section class="container">
  <div class="panel panel-default">
    <div class="panel-heading">Registered users</div>
    <!-- search box input -->
    <input type="text" [(ngModel)]='coursestat' size="40" placeholder="filter based on course: e.g Web Development">

    <!-- List group -->
    <ul class="list-group">
      <!-- pipes transforms the username's first word by capitalize it-->
      <li class="list-group-item" *ngFor="let person of personsList | filter:coursestat:'chosenCourse'">username:&nbsp;&nbsp;{{person.name | capitalize}} &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp; email:&nbsp;&nbsp;{{person.email}}
        &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp; DOB: &nbsp;&nbsp;{{person.date | date: 'd/M/y'}} &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;Address:
        &nbsp;&nbsp;{{person.address}} &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp; Course Chosen: &nbsp;&nbsp;{{person.chosenCourse
        | uppercase}}</li>
    </ul>
  </div>
</section>

//filter.pipe.ts

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

// custom pipe which filters the personsList based on the courseChosen
@Pipe({
  name: 'filter',
  pure: false
})
export class FilterPipe implements PipeTransform {

  transform(value: any, filterString: string, propName: string): any {

    if (value.length === 0 || !filterString || !propName) {
      return value;
    }

    return value.filter(_person => {
      return _person[propName] === filterString;
    });
  }

}

正如上面评论中提到的 pankaj,您应该检查值数组是否存在,如果存在则检查长度。

if (value && value.length ===  0 || !filterString || !propName) {

其次,当您应用过滤器时,您还需要检查该值是否包含其中的某些元素,添加一个条件来检查该值是否存在并且长度是否始终大于 0。

if(value  && value.length >  0){

改变你的管道, filter.pipe.ts

export class FilterPipe implements PipeTransform {
  transform(value: any, filterString: string, propName: string): any {
    if (value && value.length ===  0 || !filterString || !propName) {
      return value;
    }
    if(value  && value.length >  0){
    return value.filter(_person => {
      return _person[propName] === filterString;
    });
   }
  }
}