簡體   English   中英

angular 2 Observable完全沒有調用

[英]angular 2 Observable complete not called

我正在玩角度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的工作原理有關。 我對嗎?

searchNameStream永遠不會完成,因此從switchMap獲取的switchMap也不會完成。

每次searchNameStream發出一個事件時, heroService.getHeroesByName()調用heroService.getHeroesByName() ,並且“inner”observable發出的所有事件都被“outer”observable重新發送,直到searchNameStream發出一個新事件,並且這個過程重復。 您訂閱了外部observable,只有在searchNameStream完成時searchNameStream完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM