我有此搜索服务:
export class SearchbarComponent implements OnInit {
data: Observable<any>;
search = new FormControl();
constructor(private searchService: SearchbarService) {}
ngOnInit() {
this.data = this.search.valueChanges
.pipe(
debounceTime(1),
distinctUntilChanged(),
)
.pipe(switchMap(search =>
this.searchService.getSearchResults(search)));
}
}
在视图中,我这样做
<input placeholder="Search users here" [formControl]="search" />
<div *ngFor="let d of (data | async)" >
{{ d.name }}
</div>
它很好用,但只能在第一次使用,但是在显示第一个结果之后,此后视图就不会更新。
我在做什么错了?
答案 0 :(得分:0)
尝试
<input placeholder="Search users here" (keyup)="searchTerm$.next($event.target.value)"/>
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
export class SearchbarComponent implements OnInit{
searchTerm$ = new Subject<string>(); // <==== new
constructor(private searchService: SearchbarService) {}
ngOnInit() {
this.searchTerm$.subscribe( term => {
this.searchService.getSearchResults(q)
})
}
}
答案 1 :(得分:0)
我已经在您的代码中创建了一个工作示例库,您和我的代码之间唯一的区别是服务检查我的代码
@Injectable()
export class SearchbarService {
constructor() { }
public getSearchResults(value) {
const arr = [1,2,3,4,5,6]
return of([...arr.map(c=> Math.floor(Math.random() * 100))]); // return an observable
}
}