我有这个动态搜索栏,当您输入一个字符串时,下面会出现一个与该字符串匹配的国家/地区数组,为此,我使用了新的Subject,因此现在输入中的内容是可观察的。
按取消时,我试图清除输入的值,但是由于可以观察到,我不能只清空字符串。
我尝试了以下代码,但控制台说了
无法读取未定义的属性“值”
模板:
<div>
<h1>Country Search</h1>
<div id="search-bar">
<input #searchBox id="search-box" (input)="search(searchBox.value)" />
<button (click)="delete(search-box.value)">Cancel</button>
<ul class="search-result">
<li *ngFor="let country of countries$ | async" >
<a routerLink="/country-details/{{ country.name }}">{{ country.name }}</a>
</li>
</ul>
</div>
</div>
打字稿
import { Component, OnInit } from '@angular/core';
import { Country } from '../../interfaces/country';
import { CountrySearchService } from '../../services/country-search.service';
import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
@Component({
selector: 'app-search-bar',
templateUrl: './search-bar.component.html',
styleUrls: ['./search-bar.component.css']
})
export class SearchBarComponent implements OnInit {
selectedcountry: Country;
constructor(private countryService: CountrySearchService) { }
countries$: Observable<Country[]>;
private searchString = new Subject<string>();
search(term: string): void {
this.searchString.next(term);
}
delete(string: String) {
string = '';
console.log(string);
}
ngOnInit() {
this.countries$ = this.searchString.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term: string) => this.countryService.searchCountries(term)),
);
}
}
答案 0 :(得分:0)
您可以执行以下操作(未经测试):
export class SearchBarComponent implements OnInit {
selectedcountry: Country;
constructor(private countryService: CountrySearchService) { }
countries$: Observable<Country[]>;
private searchInput$ = new Subject<string>();
private searchClear$ = new Subject<any>();
search(term: string): void {
this.searchInput$.next(term);
}
delete(string: String) {
this.searchClear$.next();
}
ngOnInit() {
const search$ = merge(
this.searchClear$.pipe(mapTo(')),
this.searchInput$.pipe(
debounceTime(300)
)
);
this.countries$ = search$.pipe(
distinctUntilChanged(),
switchMap((term: string) => this.countryService.searchCountries(term)),
);
}
}
merge
从任一可观察结果中获取最新结果,并将其折叠为一个结果。 mapTo
与map(() => '')
基本相同。