Angular:标题搜索表单不会多次加载



我有一个标题搜索图标,它显示输入和点击按钮的小弹出窗口。若用户搜索任何输入,那个么我将把用户重定向到结果页面。我有单独的组件用于标题和搜索结果。我正在通过通用服务将搜索输入从标题传递到搜索结果。

这是第一次很好用。当我输入新的文本并搜索时,什么都不会发生。它不会将搜索输入传递给搜索结果组件,也不会再次加载搜索结果。

标题模板html

<a
#closeSearchForm
href="#"
data-title="Search"
class=""
id="dropdownMenuButton1"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
><img src="assets/images/icons/search.png" alt=""
/></a>
<span class="tooltiptext">Search</span>
<div
class="member_login search_menu_dropdown dropdown-menu"
aria-labelledby="dropdownMenuButton1"
>
<form [formGroup]="searchForm" (ngSubmit)="onSubmitSearch()"> 

<div class="search_menu_wrap">
<div class="form-group">
<input

type="text"
class="form-control"
placeholder="Search here...."
formControlName="searchInput"
[ngClass]="{ error_border: submitted1 && sf.searchInput.errors }"
/>
<div *ngIf="submitted1 && sf.searchInput.errors" class="text-danger">
<div *ngIf="sf.searchInput.errors.required">Search text is required</div>

</div>
</div>
<div class="form-group">
<button class="btn" type="submit">
Search</button>
</div>
</div>
</form>
</div>

标头ts代码

onSubmitSearch() {
this.submitted1 = true;
if (this.searchForm.invalid) {
this.loading1 = false;
return;
}
this.loading1 = true;
if (this.sf.searchInput.value) {
this.closeSearchForm.nativeElement.click();
var searchValue = this.sf.searchInput.value;
//   this.searchForm.reset();
// Object.keys(this.searchForm.controls).forEach(key => {
//   this.searchForm.get(key).setErrors(null) ;
// });
this.commonModelService.data = searchValue;
this.router.navigate(['search-results']);
}
}

通用模型服务代码-用于传递搜索输入

import { Injectable } from '@angular/core';
@Injectable()
export class CommonModelService{
data:any
}

搜索结果组件ts

ngOnInit(): void {

this.searchValue = this.commonModelService.data;
this.getSearchResults();  <!-- this function will call api and show data in html -->
}

我不明白出了什么问题。现在它只是第一次工作。搜索应该在任何时候都可以使用用户提供的任何输入。

将搜索输入从标题组件传递到搜索组件,并在用户尝试搜索时使用任何新输入在任何时间、任何页面上实现搜索功能的最佳解决方案是什么?

请提供帮助和指导。感谢

如果您已经在搜索结果中,则重定向代码将不会重新渲染组件,如果不重新渲染,search.result.component-> ngOninit将不会激发和加载结果。

你不应该直接传递数据,而应该是你的可观察和行为主体。

搜索结果组件ts

ngOnInit(): void {
this.commonModelService.search$.subscribe((searchInput) => {
if(searchInput !=== undefined){ // we want to capture empty string
this.getSearchResults()
}
})

}

通用模型服务代码-用于传递搜索输入

import { Injectable } from '@angular/core';
public search$ = new BehaviorSubject(undefined) // if undefined initially we don't do anything.
@Injectable()
export class CommonModelService{
data:any
}

BehavourSubect将在第一次订阅时返回最后一个事件值,在随后的情况下,当您已经在页面上时,它将像常规主题一样推送值。建议:每次在OnDistory 上也删除订阅

this.commonModelService.search.next(searchValue);
this.router.navigate(['search-results']);

最新更新