observable上的Angular switchMap永远不会触发

时间:2017-07-26 09:37:40

标签: angular observable

我想在Angular Tutorial中实现搜索组件。

问题:

search方法会触发并修改searchTerms: Subject<string>,但switchMap永远不会触发。

代码:

进口

import { Component, OnInit } from '@angular/core';

import { SearchService } from "./search.service";

import { Observable }        from 'rxjs/Observable';
import { Subject }           from 'rxjs/Subject';

// Observable class extensions
import 'rxjs/add/observable/of';

// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

import {Suggest} from "./suggest";

装饰

@Component({
  selector: 'search-engine',
  templateUrl: 'search-engine.component.html'
})

组件

export class SearchEngineComponent implements OnInit {

  suggestions: Observable<Suggest[]>;
  private searchTerms = new Subject<string>();

  constructor(private searchService: SearchService) {  }

  ngOnInit(): void {
    this.suggestions = this.searchTerms
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(term => {
        console.log(term);
        return Observable.of<Suggest[]>([]);
      })
      .catch(error => {
        console.log(error);
        return Observable.of<Suggest[]>([]);
      });
  }

  search(term: string): void {
    this.searchTerms.next(term);
  }
}

HTML

<input #searchBox id="search-box" (keyup)="search(searchBox.value)">

1 个答案:

答案 0 :(得分:2)

您必须订阅Observable,如果您没有订阅,则不会发生任何事情。

修改

还有另一种情况,你可以在视图中声明和观察,并通过async管道隐式订阅,这就是这里发生的事情:

<div id="search-component">
  <h4>Hero Search</h4>
  <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
  <div>
    <div *ngFor="let hero of heroes | async"
         (click)="gotoDetail(hero)" class="search-result" >
      {{hero.name}}
    </div>
  </div>
</div>

有关async管道here

的更多信息