在 Angular 中,?. 和 !. 都是安全导航操作符,用于处理可能为 null 或未定义的属性或方法。
?. 操作符是安全的管道,用于防止在引用 null 或未定义值的情况下抛出异常。它在尝试访问属性或调用方法时检查对象是否为 null 或 undefined,如果是,则返回 undefined,而不是抛出异常。
! 操作符是非空断言操作符,表示运算符右边的表达式不会为 null 或 undefined,否则会抛出异常。
下面是一个示例,展示了如何使用这两个操作符:
interface Foo {
bar?: {
baz: string;
};
}
const foo: Foo = { bar: { baz: 'hello' } };
// 使用 ?. 操作符
const result1 = foo.bar?.baz; // 'hello'
// 使用 ! 操作符
const result2 = foo.bar!.baz; // 'hello'
在上面的示例中,使用 ?. 操作符和 ! 操作符从对象 foo 中获取属性值 baz。当 foo.bar 为 null 或 undefined 时,?. 操作符返回 undefined,! 操作符会抛出异常。由于 foo.bar 是有定义的,所以两个操作符都返回 'hello'。