7

我正在玩从 Angular 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 的工作方式有关。我对吗?

4

1 回答 1

8

永远不会完成,因此从永远不会完成searchNameStream的可观察对象switchMap

每次由searchNameStream,发出一个事件时heroService.getHeroesByName(),这个“内部”可观察对象发出的所有事件都被“外部”可观察对象重新发出,直到 发出一个新事件searchNameStream,并且这个过程重复。您订阅了外部 observable,它只会在完成时searchNameStream完成。

于 2016-08-31T17:31:45.943 回答