我有標題搜索圖示,顯示輸入和單擊按鈕的小彈出視窗。如果用戶搜索任何輸入,那么我會將用戶重定向到結果頁面。我有用于標題和搜索結果的單獨組件。我正在將帶有公共服務的搜索輸入從標題傳遞到搜索結果。
這是第一次作業正常。當我輸入新文本并搜索時,什么也沒有發生。它不會將搜索輸入傳遞給搜索結果組件,也不會再次加載搜索結果。
標題模板html
<a
#closeSearchForm
href="#"
data-title="Search"
id="dropdownMenuButton1"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
><img src="assets/images/icons/search.png" alt="Angular:標題搜索表單不會多次加載"
/></a>
<span >Search</span>
<div
aria-labelledby="dropdownMenuButton1"
>
<form [formGroup]="searchForm" (ngSubmit)="onSubmitSearch()">
<div >
<div >
<input
type="text"
placeholder="Search here...."
formControlName="searchInput"
[ngClass]="{ error_border: submitted1 && sf.searchInput.errors }"
/>
<div *ngIf="submitted1 && sf.searchInput.errors" >
<div *ngIf="sf.searchInput.errors.required">Search text is required</div>
</div>
</div>
<div >
<button 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 -->
}
我不明白出了什么問題。現在它只是第一次作業。搜索應該可以隨時使用用戶提供的任何輸入進行。
將搜索輸入從標題組件傳遞到搜索組件并實作搜索功能的最佳解決方案是什么?
請幫助和指導。謝謝
uj5u.com熱心網友回復:
如果您已經在搜索結果中,您的重定向代碼將不會重新渲染組件,并且如果不重新渲染您search.result.component-> ngOninit將不會觸發并加載結果。
而不是直接傳遞資料,你應該你的 observable 和 Behavior 主題。
搜索結果組件 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']);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363683.html
上一篇:如何將用戶輸入欄位添加到URL
