在Angular中,您可以使用map
操作符和filter
操作符来忽略null值。下面是一个示例代码:
import { Component } from '@angular/core';
import { of } from 'rxjs';
import { map, filter } from 'rxjs/operators';
@Component({
selector: 'app-example',
template: '{{ result$ | async }}'
})
export class ExampleComponent {
result$;
constructor() {
this.result$ = of(1, 2, null, 4, null, 6).pipe(
filter(value => value !== null), // 使用filter操作符过滤掉null值
map(value => value * 2) // 使用map操作符对每个非null值进行操作
);
}
}
在上面的示例中,我们使用of
函数创建一个Observable,其中包含一些值和null。然后,我们使用filter
操作符过滤掉null值,然后使用map
操作符对每个非null值进行操作(在这个示例中,我们将每个值乘以2)。最后,我们将结果绑定到result$
变量,并在模板中使用async
管道订阅该Observable。
这样,我们就可以忽略null值,并对非null值进行操作。