首页 > 解决方案 > 错误类型错误:无法在角度自定义管道中读取 null 的属性“拆分”

问题描述

我收到此错误 ERROR TypeError: Cannot read property 'split' of null error while using this angular pipe and here is the code。

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

@Pipe({
  name: 'fullDate'
})
export class DatePipe implements PipeTransform {

  transform(value:any ) {
    const dateArray = value.split('-');
    const date = dateArray[2].substr(0, 1) === '0' ? dateArray[2].substr(1, 1) : dateArray[2];
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  
    return `${date} ${months[dateArray[1] - 1]} ${dateArray[0]}`;
  }

}

{{ lorem?.lorem_date | 完整日期}}

在此处输入图像描述

标签: angularangular-pipepipes-filters

解决方案


该错误意味着您正在拆分一个为空的值,因此您只需添加一个检查即可。

试试这样:

transform(value:any ) {
   if(value){ 
        const dateArray = value.split('-');
        const date = dateArray[2].substr(0, 1) === '0' ? dateArray[2].substr(1, 1) : dateArray[2];
        const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

        return `${date} ${months[dateArray[1] - 1]} ${dateArray[0]}`;
    }
  }

推荐阅读