我正在创建一个NgRx应用程序,但是对它的实现感到困惑,因为这是我第一个使用NgRx的应用程序。
我有一个带有"公司"状态的存储。 我需要搜索公司并在找到时返回。
如果未找到所需的公司,则应调用API并获取结果,但该过程是循环的并且运行无限时间。
以下是我的代码:
以下是我的代码:
this.companySearchCtrl.valueChanges
.pipe(
debounceTime(300),
distinctUntilChanged()
)
.subscribe(val => {
if (val !== ' ' || val !== '') {
this.store.select(getCompanys).subscribe(data => {
console.log(data);
//filter companies on the basis of search text
const filteredData = data.filter(x =>
x['name']
.toLowerCase()
.startsWith(this.companySearchCtrl.value.toLowerCase())
);
console.log(filteredData);
if (filteredData.length === 0) { //if data is not found in store
console.log('got a call');
this.store.dispatch(
new CompanyActions.find({
where: { name: { regexp: `${val}/i` } } // call to API to search with regExp
})
);
} else {
// if required data found in store
console.log('got no call');
this.filteredCompanies$ = of(filteredData);
}
});
}
});
如果在存储中找到数据,则此过程运行正常。如果在存储中没有找到数据或API调用没有返回结果,则会无限运行。如何使其正确?