初始值可提供给
startWith
接线员,正如现在删除的答案中所提到的。
问题是
filterLocation$
分配得太晚,之后
filterLocation$ | async
被评估为
null
. 由于更改发生在同一个勾号上,这会导致更改检测错误(尽管
ExpressionChangedAfterItHasBeenCheckedError
如果预期会发生,则可以视为警告)。
解决方案是将代码从
ngAfterViewInit
到
ngOnInit
,在触发更改检测之前。
这并不总是可能的。另一种方法是异步提供一个值,这样它就不会干扰初始更改检测。
通过延迟整个可观测的
delay
运算符(用户输入的可接受解决方案,因为它不是时间关键的):
this.filterLocation$ = fromEvent(searchBox, 'input')
.pipe(
map((e: any) => {
const value = e.target.value;
return value ? this.locations
.filter(l => l.toLowerCase().includes(value.toLowerCase()))
: this.locations;
}),
startWith(this.locations),
delay(0)
)
或者通过使初始值与调度程序异步:
import { asyncScheduler } from 'rxjs'
...
this.filterLocation$ = fromEvent(searchBox, 'input')
.pipe(
map((e: any) => {
const value = e.target.value;
return value ? this.locations
.filter(l => l.toLowerCase().includes(value.toLowerCase()))
: this.locations;
}),
startWith(this.locations, asyncScheduler)
)