我创建了一个具有搜索功能的组件,该组件调用api并在页面上显示数据。获得搜索结果后,将它们存储在localStorage中,以便在您导航回到相同的搜索组件页面时恢复数据。一切工作正常,直到我将存储的数据分配回formEvent可观察的结果属性this.searchResult $为止。问题是一旦我通过其他路线返回到同一页面,fromEvent将不再触发。
ngOnInit() {
const searchEvent$ = fromEvent<any>(this.inputSearch.nativeElement, 'keyup').pipe(tap(() => { console.log('working'); }));
this.searchResult$ = searchEvent$
.pipe(
tap(() => { this.isDataOn = true }),
map(event => event.target.value),
filter(value => value ? true : false),
switchMap(search => this.notesService.onSearchNotes(search)))
)
if (!this.isDataOn) {
this.refreshData()
}
}
refreshData() {
if (localStorage.getItem("queryStack")) {
const data = JSON.parse(localStorage.getItem("queryStack") || "[]");
console.log(data);
this.searchResult$ = of(data);
}
}
答案 0 :(得分:1)
尝试以下方法,该方法将本地存储中保存的所有数据与从服务器获取的响应击键事件的结果合并。
// in your imports
import { merge } from 'rxjs';
ngOnInit() {
const searchEvent$ = fromEvent<any>(this.inputSearch.nativeElement, 'keyup').pipe(tap(() => { console.log('working'); }));
this.searchResult$ = merge(
of(this.getSavedData()),
searchEvent$
.pipe(
map(event => event.target.value),
filter(Boolean),
debounceTime(1000),
distinctUntilChanged(),
switchMap(search => this.notesService.onSearchNotes(search))
)
);
}
getSavedData() {
const localStorageValue = localStorage.getItem("queryStack") || "[]";
try {
return JSON.parse(localStorageValue);
} catch (ex) {
console.error('Error parsing JSON:', ex);
return [];
}
}