(已关闭)无法观察搜索在Angular2中检索init上的所有数据

时间:2017-05-04 21:45:28

标签: angular typescript rxjs observable

我一直致力于个人应用。我想在第一次初始化我的组件时检索所有用户数据。我想我无法工作,因为我的searchTerms正在避开我的主题字符串。我尝试在this.searchTerms.next('');方法中使用onInit,但没有运气。如果我输入用户名并稍后将其删除,则会显示用户列表,因为switchMap的else块已执行。

我的组件:

export class UserComponent implements OnInit {

  users: Observable<User[]>;
  private searchTerms = new Subject<string>();

  getUsers(): void {
    this.users = this.searchTerms
      .debounceTime(300)        // wait 300ms after each keystroke before considering the term
      .distinctUntilChanged()   // ignore if next search term is same as previous
      .switchMap(term => term   // switch to new observable each time the term changes
        // return the http search observable
        ? this.userService.search(term)
        // or the observable of all users if there was no search term
        : this.userService.search(''))
      .catch(() => {
        return Observable.of<User[]>([]);
      });
  }

  ngOnInit(): void {
    this.getUsers();
  }

  search(term: string): void {
    // Push a search term into the observable stream.
    this.searchTerms.next(term);
  }

我的模板:

...
<h4>User Search</h4>
    <input #userSearchBox id="user-search-box" (keyup)="search(userSearchBox.value)" />
...
<div *ngFor="let user of users | async" class="input-group">
...

2 个答案:

答案 0 :(得分:0)

我想你想要像

这样的东西
import 'rxjs/add/operator/startWith';

export class UserComponent implements OnInit {

  searchTerms = new Subject<string>();

  searchTerm$ = this.searchTerms.asObservable().startWith('');

}

答案 1 :(得分:0)

修复了我的问题添加了循环方法ngAfterViewInit和以下代码:

ngAfterViewInit(): void {
  this.searchTerms.next('');
}

我的问题是时间问题,我很快就打电话给订阅了。谢谢您的帮助。