【发布时间】:2021-03-14 14:57:52
【问题描述】:
这是我的烟斗:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'transformFullName'
})
export class TransformFullNamePipe implements PipeTransform {
transform(value: string, ...args: unknown[]): string {
let fullName: string[] = value.split(' ');
fullName[0].charAt(0).toLocaleUpperCase();
fullName[1].charAt(0).toLocaleUpperCase();
console.log(fullName);
if (fullName[0].length + fullName[1].length > 41) {
return fullName[0].charAt(0) + '. ' + fullName[1].charAt(0) + '.';
}
return fullName[0] + ' ' + fullName[1];
}
}
我上了游戏机:
(2) ["male", "male"]
0: "male"
1: "male"
length: 2
__proto__: Array(0)
还有一个错误:core.js:6157 ERROR TypeError: Cannot read property 'charAt' of undefined 在 TransformFullNamePipe.transform (transform-full-name.pipe.ts:11)。为什么?
【问题讨论】:
-
你能创建一个stackblitz
-
我认为错误来自没有第二名的字符串中的空格。要解决它,您可以像
value.trim().split(' ');那样添加trim- 请参阅下面的评论 -
@Szyszka947 另外,检查 fullName 的长度。