Issue with Angular 2 Observable not triggering the complete function

I've been experimenting with the hero app tutorial for Angular 2 and currently have this Component set up:

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);
    }

}

The issue I'm encountering is that, according to my understanding, the subscribe method takes three callback parameters

.subscribe(success, failure, complete);
. However, in my case, the complete part is never executed. Could this be related to how switchMap functions? Am I on the right track?

Answer №1

The observable generated from the searchNameStream stays active indefinitely, resulting in an ongoing stream of events and causing the observable created by switchMap to remain perpetual as well.

Each time a new event is triggered by the searchNameStream, the method heroService.getHeroesByName() is invoked. The emitted events from this internal observable are then relayed by the primary (outer) observable until a fresh event emerges from the searchNameStream, starting the cycle anew. By subscribing to the outer observable, you ensure that it will persist until the underlying searchNameStream eventually reaches completion.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refine the observable data

Trying to filter a list of items from my Firebase database based on location.liked === true has been a challenge for me. I've attempted using the traditional filter array method but have not had success. Can anyone suggest an alternative method to acc ...

Determining the parent type in Typescript by inferring it from a nested member

Typescript has the ability to infer the type of a value based on queries made within if statements. For instance, the type of one member of an object can be deduced based on another: type ChildType = 'a' | 'b'; type Child<T extends ...

Do you need to finish the Subject when implementing the takeUntil approach to unsubscribing from Observables?

In order to prevent memory leaks in my Angular application, I make sure to unsubscribe from Observables using the following established pattern: unsubscribe = new Subject(); ngOnInit() { this.myService.getStuff() .pipe(takeUntil(this.unsubscr ...

When TypeScript generator/yield is utilized in conjunction with Express, the retrieval of data would not

Trying to incorporate an ES6 generator into Express JS using TypeScript has been a bit of a challenge. After implementing the code snippet below, I noticed that the response does not get sent back as expected. I'm left wondering what could be missing: ...

Exploring the combination of Angular and Redux on windows devices

Upon running ng serve, I encountered the following error: The class NgRedux<RootState> has been incorrectly implemented as interface ObservableStore<RootState>. The property [Symbol.observable] is missing in type NgRedux<RootState> but i ...

Creating an Angular 2 component that utilizes an interface within the constructor

If you have an interface named IData, and you want to develop an Angular 2 component that can accept any Class utilizing IData in its constructor, could this concept be implemented or is it off track? Your insights are greatly appreciated. ...

Utilize rxjs to effectively handle API data responses and efficiently manage the state of your application within Angular 10

I'm currently exploring the most efficient method for storing and updating data from an API, as well as sharing that data among sibling components. Here's my initial attempt: Storing the Observable export class MyExampleService { private data ...

Utilizing Typescript to Transfer Data from Child to Parent in React

Attempting to pass data from a Child Component to a Parent component using Typescript can be challenging. While there are numerous resources available, not all of them delve into the TypeScript aspect. One question that arises is how the ProductType event ...

The new data is not being fetched before *ngFor is updating

In the process of developing a "Meeting List" feature that allows users to create new meetings and join existing ones. My technology stack includes: FrontEnd: Angular API: Firebase Cloud Functions DB: Firebase realtime DB To display the list of meeting ...

Ways to determine the presence of a value in an array

Here is an example array: [ {practitioner: "place_1509136116761", H0709: false, H0911: false, H1113: false, H1315: false}, {practitioner: "place_1509136116772", H0709: true, H0911: false, H1113: true, H1315: false}, {practitioner: "place_15091361166 ...

Strategies for adding elements to a FormArray in Angular 4

I am currently working on a dynamic Angular form that displays like this. <form [formGroup]="myForm"> <div *ngFor="let Repo of Repos;"> <fieldset> <legend>{{Repo.name}}</legend> ...

Can't figure out why the BackgroundImage URL from process.env isn't appearing on my website

Having trouble setting a background image on my website that connects with my backend to determine which image should appear. However, in some cases, the image isn't showing up. When attempting to add a background image using the code below within a ...

Retrieving Data from Angular Component within a Directive

Currently, I am in the process of creating an "autocomplete" directive for a project. The aim is to have the directive query the API and present a list of results for selection. A component with a modal containing a simple input box has been set up. The ob ...

The logout feature experiences a malfunction when invoked from the app.component.ts file

I have an authentication Service with a Logout() function implemented as shown below: export class AuthService { isAuthenticated = new BehaviorSubject(false); constructor(private router: Router) { } Logout() { console.log('Logout'); ...

In Next.js, I am experiencing an issue where the Tailwind class is being added, but the corresponding

I'm currently in the process of developing a board game where I need to track players and their positions on specific squares. My goal is to display a small colored dot on the square where each player is positioned. Here's a snippet of my templa ...

Exploring Angular 5: Managing HTTP Headers and Utilizing URL Parameters

I am currently working on an Angular project that involves third-party authentication, which redirects to our app with additional information in the HTTP headers. Here are the questions I have: What is the best way to extract the information from the HT ...

Using ngFor to Filter Tables in Angular 5

Are you in the midst of implementing multiple data filters in an Angular Application that displays data using a Table and ngFor? You may have explored different methods such as using Pipe in Type Script, but discovered that it is not recommended accordin ...

Is it possible to transform a reference to a React Component into JSON format?

I am looking to serialize the state of a React component into JSON format and save it in a database. Here is the current structure of my code: const [exampleState, setExampleState] = useState([ { componentName: "Test component", co ...

Developing Angular 6 for dynamic HTML navigation tabs

Being new to Angular 6, I recently created tabs in HTML and now need to convert them into Angular 6 while also making them dynamic. Here is the original HTML code: <ul class="nav nav-tabs side_nav" role="tablist"> <li role="presentation" class= ...

Ending the connection in SignalR upon $destroy

I am currently working on a page that is utilizing SignalR, Angular, and Typescript. Upon the destruction of the current $scope (such as during a page change), I make an attempt to disconnect the client from the SignalR server: Controller.ts $scope.$on(&q ...