complete() method is not triggered by Observable

Note: I understand that there is a timer observable from rxjs, but for the purpose of this project, I am using it as a proof of concept to enhance my understanding of observables.

In my Angular application, I have developed a timer with a start button, a display showing the elapsed seconds, and another display indicating the current state (stopped/executing/finished).

Upon clicking the start button, the example begins running, the state changes to "executing," and the seconds increment. However, when it reaches 5 seconds, it stops (displaying "finishing" in the log) without transitioning to "finished" (and the "finished" console log does not appear). Also, the error method is not triggered.

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

@Component({
  selector: 'app-reloj',
  templateUrl: './reloj.component.html',
  styleUrls: ['./reloj.component.css']
})
export class RelojComponent implements OnInit {

  public time: number = 0;
  public state: string = "Stopped";
  private crono = new Observable<number>(
    observer => {
      let start: number = (new Date()).getTime();
      let lastCount = 0;
      (function repeat() {
        let now: number = (new Date()).getTime();
        let seconds = ((now - start) / 1000 | 0);
        if (lastCount < seconds) {
          observer.next(seconds);
          if (seconds >= 5) {
            console.log("Finishing");
            return;
          }
          lastCount = seconds;
        }
        setTimeout(
          repeat,
          100);
        })();
    });

  constructor() { }

  ngOnInit(): void {
  }

  onStart(): void {
    console.log("Starting");
    let self = this;
    this.state = "Executing";
    this.crono.subscribe({
      next(seconds: number) {
        console.log(`At next ${seconds}`);
        self.time = seconds;
      },
      error(err) {
        console.log("Error");
      },
      complete() {
        console.log("Finished");
        self.state = "Finished";
      }
    })
  }
}

and the html

<button (click)="onStart()">Start</button>
<div>{{time}}</div>
<div>{{state}}</div>

Answer №1

To indicate to the subscriber that the task is finished, make sure to call the observer's complete() method.

if (seconds >= 5) {
        console.log("Finishing");
        observer.complete();
        return;
      }

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

Angular2's change detection mechanism does not behave as anticipated after receiving a message from a Worker

Within my angular2 application, I encountered a rather intriguing scenario which I will simplify here. This is AppComponnet export class AppComponent { tabs: any = []; viewModes = [ { label: "List View"}, { label: "Tree View" }, ...

Turning a JSON string into interpolation within an Angular application

I received a JSON response that looks like this: { someText: "Order in {000} 12pm PST for early shipping"; cutofftime : "10000000" } What is the most effective way to replace the '{000}' with the dynamic value stored in &quo ...

typescript makeStyles() functions from material-ui library

I've been struggling to find the correct type without relying on any. I have a working code that styles the component as expected: import { makeStyles } from '@material-ui/core/styles' const useStyles = makeStyles((theme) => ({ mainC ...

How to properly handle Angular routing errors and best practices?

Currently, I have been delving into learning Angular to integrate with my Ruby on Rails application. However, I have encountered some challenges specifically related to routing. Here is a snippet from my app.routing file: import { NgModule } from '@ ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Is it possible to use square brackets in conjunction with the "this" keyword to access a class property using an expression?

export class AppComponent implements OnInit { userSubmitted = false; accountSubmitted = false; userForm!: FormGroup; ngOnInit(): void {} onSubmit(type: string): void { this[type + 'Submitted'] = true; if(this[type + 'For ...

"Caution: The `className` property did not align" when configuring a theme provider within Next.js

I'm currently working on developing a theme provider using the Context API to manage the application's theme, which is applied as a className on the body element. The implementation of the context is quite straightforward. When initializing the ...

Exploring the depths of nested JSON with Angular2

I'm a beginner in Angular 2 using Typescript. I am trying to figure out how to access the 'D' and 'G' elements in my JSON data using NgFor. Is there a specific way or method that I can use to achieve this? [ { "A":"B", "C" ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

Default functionality of Typescript paths imports fails to operate properly

Can anyone help me figure out how to set up default imports in my .ts files using the paths specified in my tsconfig.base.json? I have this file defined as default in the File Type > Typescript Config. https://i.sstatic.net/LvBGV.png The import statem ...

Encountering an Issue with Passing Props through Gatsby Link to Access a Prop on the

I am encountering an issue when trying to pass a value to another page for conditional rendering. The bug I'm facing is related to 'location' being undefined during the build process. Despite my efforts, I have been unable to resolve this is ...

"What is the method for verifying if a value is not a number in Angular 2

While attempting the following: dividerColor="{{isNaN(+price) ? 'warn' : 'primary'}}" An error is being thrown: browser_adapter.ts:82 ORIGINAL EXCEPTION: TypeError: self.context.isNaN is not a function Is there a way to determine ...

Limiting access to the Google API key so that it is only usable within specific areas of the application

Incorporating both the Google Places and Distance Matrix API into my Angular 8 application has been a key aspect of its functionality. Initially, I attempted to limit access to the API by specifying the application URL () on the Google Cloud Platform. Su ...

Learn how to set expectations on the object returned from a spied method, Jasmine

I am currently faced with setting an expectation regarding the number of times a specific function called "upsertDocument" is executed. This function is part of a DocumentClient object within a getClient method in production. Here's how it looks: cli ...

Angular ng2-date-picker: Using an icon click to open the date picker

Is there a way to trigger the ng2-date-picker to open when clicking on the calendar icon? I am currently utilizing this npm package in my Angular project: https://www.npmjs.com/package/ng2-date-picker ...

Creating specialized validation for numeric fields in Angular2

Attempting to implement custom validation in Angular 2 has been a challenge for me. I have followed the necessary steps based on my understanding, but still struggling to get it working. import { FORM_DIRECTIVES, AbstractControl, ControlGroup ,FormBuilder ...

Creating a custom Angular 2 component with specified HTML template content

I am currently working with Angular 2 and @ng-bootstrap. In my project, I have a modal dialog set up as follows: <template #editDialog let-c="close" let-d="dismiss"> <div class="modal-header"> <button type="button" class="close" ...

Refreshing rows in ngx-datatable

Just started using ngx-datatable (version 11) with Angular-5 and encountered an issue. When loading rows during ngInit, everything works fine. However, when lazy-loading due to a user search request, the table shows the correct total number of rows but onl ...

The setInterval function continues executing even after the page has been changed

I'm encountering an issue with my function where it continues to run even after the page has changed, resulting in an error. How can I go about stopping this behavior? Thank you! componentDidMount() { var current = 0; var slides = document.g ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...