angular - 错误类型错误:无法在角度自定义管道中读取 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 | 完整日期}}
解决方案
该错误意味着您正在拆分一个为空的值,因此您只需添加一个检查即可。
试试这样:
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]}`;
}
}
推荐阅读
- javascript - 如何在javascript中列出2的幂
- machine-learning - Knime 工具组件 Gradient Boosted Trees Predictor 面临错误
- bash - 带有位置参数的shell脚本问题,如果有的话
- ios - Apple 评论 React Native “发生未知错误”
- java - 线程“main”中的异常 java.lang.NullPointerException selenium maven junit
- javascript - 无论如何运行Node JS PATCH请求
- python - numpy expand_dim() 中的 (13027,) 和 (13027,1) 有什么区别
- r - 将 db 文件加载到 R 中耗尽内存的好技巧是什么?
- python - 如何 - 将列表中的每个项目复制到另一个数据库(RPA - Python)
- excel - 尝试将(仅)唯一值从列传递到 VBA 中的字典。验证未发生。我错过了什么?