我正在玩角度2教程的英雄应用程序,现在我有这个组件
import { Component, OnInit } from '@angular/core'
import { Subject } from 'rxjs/Subject';
import { Hero } from "./hero";
import { Router } from "@angular/router";
import { HeroService } from "./hero.service";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
@Component({
selector: 'hero-search',
templateUrl: 'app/hero-search.component.html',
styleUrls: ['app/hero-search.component.css'],
})
export class HeroSearchComponent implements OnInit{
heroes: Hero[];
isLoading: BehaviorSubject<boolean> = new BehaviorSubject(false);
error: any;
private searchNameStream = new Subject<string>();
constructor(
private heroService: HeroService,
private router: Router
) {}
ngOnInit() {
this.searchNameStream
.debounceTime(400)
.distinctUntilChanged()
.switchMap(name => {
this.isLoading.next(true);
return this.heroService.getHeroesByName(name)
})
.subscribe(
heroes => this.heroes = heroes,
error => this.error = error,
() => {
console.log('completed');
this.isLoading.next(false);
})
}
// Push a search term into the observable stream.
search(Name: string): void {
this.searchNameStream.next(Name)
}
gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
}
问题是,如果我理解正确,订阅需要三个回调参数.subscribe(success, failure, complete);
。但就我而言,完整的部分永远不会被执行。我想这与switchMap的工作原理有关。我是对的吗?
答案 0 :(得分:5)
The searchNameStream
never completes, so the observable obtained from switchMap
never completes either.
Every time an event is emitted by the searchNameStream
, heroService.getHeroesByName()
is called and all the events emitted by this "inner" observable are reemitted by the "outer" observable, until a new event is emitted by the searchNameStream
, and this process repeats. You subscribed to the outer observable, which will only complete when the searchNameStream
completes.