代码之家  ›  专栏  ›  技术社区  ›  AlexFF1

Angular 4管道无法读取未定义的属性“toLowerCase”

  •  1
  • AlexFF1  · 技术社区  · 8 年前

    我已经实现了以下过滤器/管道以大写第一个字母,并导入到模块中。ts等。

    管ts

    import { Pipe, PipeTransform } from '@angular/core';
    
    
    @Pipe({name: 'capitalize'})
    export class CapitalizePipe implements PipeTransform {
    
       transform(str:any) {
    
         var splitStr = str.toLowerCase().split(' ');
        for (var i = 0; i < splitStr.length; i++) {
    
            splitStr[i] = splitStr[i].charAt(0).toUpperCase() + 
            splitStr[i].substring(1);     
        }
        // Directly return the joined string
        return splitStr.join(' '); 
       }
     }
    

    一切都很好,除非我在这个表达式中使用它- 无法读取未定义的属性“toLowerCase”

     {{messageItem?.cc && messageItem?.cc[0]?.name | capitalize}}
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Sajeetharan    8 年前

    在管道中添加null/未定义的检查,以检查字符串在调用之前是否为null .toLowerCase

    if (str === undefined) return [];
    
        2
  •  0
  •   Sachila Ranawaka    8 年前

    管道执行初始值为null,因为这是异步的。你需要处理 undefined 变量

    var splitStr = str.toLowerCase().split(' ') || []