过滤器不起作用:错误无法读取 null 的属性“toLowerCase”

时间:2021-04-20 22:40:01

标签: angular

我有一个过滤器搜索应用程序,我通过 spring API 从 MySQL 数据库中提取数据。一切都运行良好,但由于我在 filterExpenses() 中实现了 list-expense.component.ts 方法,因此出现错误

<块引用>

“类型错误:无法读取 null 的属性 'toLowerCase'”

它指出错误在于该行:

return e.expense.toLowerCase().includes(this.filters.keyword.toLowerCase());

关于如何摆脱这个错误,我没有成功。

如果有人可以帮助我,不胜感激。

费用.ts(服务)

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Expense } from '../models/expense';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class ExpenseService {
  private getUrl: string = 'http://localhost:8080/api/v1/expenses';
  constructor(private httpClient: HttpClient) {}

  getExpenses(): Observable<Expense[]> {
    return this.httpClient
      .get<Expense[]>(this.getUrl)
      .pipe(map((response) => response));
  }

  getExpense(id: number): Observable<Expense> {
    return this.httpClient
      .get<Expense>(`${this.getUrl}/${id}`)
      .pipe(map((response) => response));
  }
}

list-expense.component.ts

import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Expense } from 'src/app/models/expense';
import { ExpenseService } from 'src/app/services/expense.service';

@Component({
  selector: 'app-list-expense',
  templateUrl: './list-expense.component.html',
  styleUrls: ['./list-expense.component.css'],
})
export class ListExpenseComponent implements OnInit {
  filters = {
    keyword: '',
  };
  expenses: Expense[];
  constructor(private expenseService: ExpenseService) {}

  ngOnInit(): void {
    this.listExpenses();
  }

  listExpenses() {
    this.expenseService
      .getExpenses()
      .subscribe((data) => (this.expenses = this.filterExpenses(data)));
  }

  filterExpenses(expenses: Expense[]) {
    return expenses.filter((e) => {
      // Error on this line
      return e.expense
        .toLowerCase()
        .includes(this.filters.keyword.toLowerCase());
    });
  }
}

list-expense.component.html

<a routerLink="/addexpense">Add Expense</a>

<input type="text" [(ngModel)]="filters.keyword" name="keyword" (input)="listExpenses()">

<div *ngFor="let expense of expenses">
  <h3>{{expense.expense}}</h3>
  <h3>{{expense.amount | currency: 'CHF'}}</h3>

  <a routerLink="/editexpense/{{expense.id}}">Edit</a>
  <button (click)="deleteExpense(expense.id)">Delete</button>
</div>
<a routerLink="/addexpense">Add Expense</a>

<input type="text" [(ngModel)]="filters.keyword" name="keyword" (input)="listExpenses()">

<div *ngFor="let expense of expenses">
  <h3>{{expense.expense}}</h3>
  <h3>{{expense.amount | currency: 'CHF'}}</h3>

  <a routerLink="/editexpense/{{expense.id}}">Edit</a>
  <button (click)="deleteExpense(expense.id)">Delete</button>
</div>

2 个答案:

答案 0 :(得分:1)

如果您收到“TypeError: Cannot read property 'toLowerCase' of null”错误,这意味着您正在执行“toLowerCase”函数的值不是字符串。 e.expense 很可能不是字符串、数字或空值。尝试打印 e.expense 的值并查看问题所在。

答案 1 :(得分:1)

这很可能发生,因为数组中有一个对象的 expensenull

因此请考虑使用 Typescript Optional Chaining,以便当 e.expensenull 时,它不会尝试执行 toLowerCase() 方法。

所以这条线应该是这样的

return e.expense?.toLowerCase().includes(this.filters.keyword.toLowerCase());

你也可以像这样使用简单的 if 语句

filterExpenses(expenses: Expense[]) {
  return expenses.filter((e) => {
    if (!e.expense) {
      return;
    }
    return e.expense
      .toLowerCase()
      .includes(this.filters.keyword.toLowerCase());
  });
}