Execute the function right away and then at regular intervals of X seconds

Need help with Angular 7 function call timing

checkData(): Observable<string> {
    return this.http.get('')
        .pipe(
            map(res => {
                let result;
                result = {
                    packageNumber: this.packageNumber,
                };
                return result;
            })
        );
}

In my component, I'm attempting to auto-call the function:

private killTrigger: Subject<void> = new Subject();
private fetchData$: Observable<string> = this.packageService.checkData();

private refreshInterval$: Observable<string> = timer(0, 1000)
    .pipe(
        takeUntil(this.killTrigger),
        switchMap(() => this.fetchData$),
        catchError(error => of('Error'))
    );

Any suggestions on how to get it working?

Answer №1

To activate this feature, you must first subscribe to it. The most efficient way to do so is:

// defining class
private subscription: Subscription;
// in NgOnInit
this.subscription = this.refreshInterval$.subscribe(noop)
// in NgOnDestroy
this.subscription.unsubscribe(); // preventing memory leaks

In order to trigger your fetchData$, simply replace the switchMap call with:

map(() => this.fetchData$.subscribe(noop),

If you fail to subscribe to the observable, it will not be activated. There is no need for switchMap in this situation.

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

What is the best way to first identify and listen for changes in a form

In Angular, there are reactive forms that allow you to track changes in both the complete form and specific fields: this.filterForm.valueChanges.subscribe(() => { }); this.filterForm.controls["name"].valueChanges.subscribe(selectedValue => { }); ...

Exploring the Power of Nested *ngFor in Angular 2

I am struggling with passing indexes to a function where the first parameter (ii) is coming back as undefined. <div *ngFor="let tab of screen.data.tabs; let indexTab = i;"> <div *ngIf="tab.active"> <div *ngIf="tab.questions"&g ...

What is the best way to add a clickable link/button in Angular 8 that opens a webpage in a new tab?

I'm looking to create a website that opens in a new tab when a link or button is clicked. I'm unsure how to achieve this in Angular 8. ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

Express is encountering an issue where it is unable to interpret the property 'name' of an undefined element coming from

I am attempting to create a fullstack application using Node.js and Angular with Material UI. I have encountered an issue while working on my web resource management application. Currently, I am facing an error during the registration and data submission ...

When the first element of an array is undefined, Angular's ngFor will not render anything

We have an array called stringArray: var stringArray = new Array(); stringArray[1] = 'one'; In Angular, the ngFor directive displays nothing when stringArray[0] is undefined. How can this issue be resolved? ...

Heroku local is designed to support only NodeJS applications, without any Angular framework or database connectivity

I'm currently facing two separate issues. When I run my app locally, it works fine, but it doesn't function properly on Heroku. Running "heroku local" opens the NodeJS app on localhost:5000 and connects to the local database. However, when attemp ...

Understanding Scope in TypeScript

Recently, I developed a sample application in Node.js which utilizes pg-promise to execute queries on a Postgres database. I encapsulated this functionality within a class named PostgresDataAccess. However, I encountered an issue while trying to access t ...

Issues with the 'GET' request functionality on the deployed Angular project

I am attempting to run an Angular project that I have built. After copying the folder generated from 'ng build' and placing it in the directory where my back end code (using express) is located, I am trying to run it on my laptop at port 3000. Wh ...

Typing should be positioned on either side of the declaration

When I define the type MyType, it looks like this: export type MyType = { ID: string, Name?: string }; Now, I have the option to declare a variable named myVar using three slightly different syntaxes: By placing MyType next to the variable ...

Leveraging File functionality in TypeScript

In the process of developing a web application with Angular 4 and Typescript, I encountered an issue while attempting to retrieve the date of a file for upload. Specifically, when trying to access the lastModified property of a File object, Typescript retu ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

Error: JSON encountered circular structure when attempting to serialize an object of type 'ClientRequest' with a property 'socket' that references an object of type 'Socket'

Encountering an error while attempting to make a POST request to my TypeORM API using axios: TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest' | property 'socket' -&g ...

How to Activate Angular Material Select with FormControl

Looking to implement an Angular material select dropdown with a custom trigger. Here is the desired select dropdown example: https://stackblitz.com/angular/omvmgjjbnnq?file=app%2Fselect-custom-trigger-example.ts Below is my code snippet : component.ts ...

Troubleshooting the issue of conditional extension in Typescript for "Array or Object" not functioning as anticipated

My goal is to create a TypeScript type generic that has the following structure: type APIDataShape<T extends { id: unknown } | Array<{ id: unknown }>> = T extends Array<any> ? Array<{ id: T[number]["id"]; ...

Unlock the Full Potential of TypeScript: Seamless Export of Classes and Functions

In my AngularJS project, I have a separate JavaScript file where I declare prototype functions. Here's an example: function lastConv(){ this.item1="2" this.message="hello" ...... } lastConv.prototype.setupfromThread(data) { this.currentBox = dat ...

Refresh the information in the <ion-datetime> component by utilizing the formGroup

I am currently working with a form that has been created using 'FormBuilder'. The form includes a date control and I am trying to figure out how to update the data in that control using the patchValue() method. In the template, the control has d ...

Utilizing Custom Validators in Angular to Enhance Accessibility

I'm struggling to access my service to perform validator checks, but all I'm getting is a console filled with errors. I believe it's just a syntax issue that's tripping me up. Validator: import { DataService } from './services/da ...

When navigating to a new component using routerLink in Angular, the previous component is also loaded. This

I am facing an issue with my sign-in page and sign-up button. When the button is clicked, it should route to /sign-up. My expectation is that only the sign-up component should be displayed on the /sign-up page, but in reality, both the sign-up and sign-in ...

Setting a dynamic routerLink in Angular 2 based on a component's property-value

Recently, I developed a component with a <a> element and a routerLink property that I intended to set from the template in which the component is used. However, when attempting to do so, I encountered an error message stating 'Cannot read proper ...