"Implementing a call and waiting at intervals by utilizing the subscribe function in Angular 6

In my code, I have a method that is called every 10000 times. Now, I want to modify this so that the function getAllNotificationsActed0() is invoked every 10 seconds. If the data does not arrive within this interval, I do not want the function to be called again. Only when the data arrives within 10 seconds should the function be executed; otherwise, it should wait.

service.ts

public NotifGetAllActedNoActive(): Observable<Notifications[]> {
  let headers = new Headers();
  headers.append('x-access-token', this.auth.getCurrentUser().token);
  return this.http.get(Api.getUrl(Api.URLS.NotifGetAllActedNoActive), {
    headers: headers
  })
    .map((response: Response) => {
      let res = response.json();
      if (res.StatusCode === 1) {
        this.auth.logout();
      } else {
        return res.StatusDescription.map(notiff => {
          return new Notifications(notiff);
        });
      }
    });
}

component.ts

ngOnInit() {
  this.subscription = Observable.interval(10000).subscribe(x => {
    this.getAllNotificationsActed0();
  });
}

getAllNotificationsActed0() {
  this.notif.NotifGetAllActedNoActive().subscribe(notification0 => {
    this.notification0 = notification0;
    if (this.isSortedByDate) {
      this.sortbydate();
    }
  });
}

Any suggestions for improvement?

Answer №1

Here's a suggestion for your component implementation:

import { takeUntil } from 'rxjs/operators';
import { Subject, timer } from 'rxjs';

private _destroy$ = new Subject();
ngOnInit() {
    this.getAllNotificationsActed0();
}
ngOnDestroy() {
    this._destroy$.next();
}
getAllNotificationsActed0() {
    this.notif.NotifGetAllActedNoActive()
     .pipe(takeUntil(this._destroy$))
     .subscribe(notification0 => {
        this.notification0 = notification0;
        if (this.isSortedByDate) {
            this.sortbydate();
        }
        timer(10000).pipe(takeUntil(this._destroy$))
            .subscribe(t => this.getAllNotificationsActed0() );
    });
}

To prevent memory leaks and stop pipes on component destruction, using a Subject object is a recommended approach. This allows you to effectively manage and terminate any ongoing processes within your component.

Answer №2

Give this a shot

To track the waiting request, you can maintain a flag

//New Flag
requestWaiting : boolean = false;

public NotifGetAllActedNoActive(): Observable<Notifications[]> {
let headers = new Headers();
headers.append('x-access-token', this.auth.getCurrentUser().token);
return this.http.get(Api.getUrl(Api.URLS.NotifGetAllActedNoActive), {
  headers: headers
})
  .map((response: Response) => {
    this.requestWaiting = false;
    let res = response.json();
    if (res.StatusCode === 1) {
      this.auth.logout();
    } else {
      return res.StatusDescription.map(notiff => {
        return new Notifications(notiff);
      });
    }
 });
}

Utilize the flag when calling the method periodically

ngOnInit() {
  this.subscription = Observable.interval(10000).subscribe(x => {
     if(!this.requestWaiting){
         this.requestWaiting = true;
         this.getAllNotificationsActed0();
     }
  });
}
  getAllNotificationsActed0() {
    this.notif.NotifGetAllActedNoActive().subscribe(notification0 => {
      this.notification0 = notification0;
      if (!this.isSortedByDate) {
        this.sortbydate();
      }
    });
  }

The observable that has already been triggered will wait for the response. Hopefully, this solution is beneficial to you

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

In order to iterate through a 'IterableIterator<number>', you must either enable the '--downlevelIteration' flag or set the '--target' to 'es2015' or newer

While attempting to enhance my Slider, I encountered an error when utilizing TypeScript React within this Next.js project: "Type 'IterableIterator' can only be iterated through when using the '--downlevelIteration' flag or with a ...

Can you use `keyof` to create a template literal type?

Defined a form schema type example: type FormSchema = { username: string; settings: { theme: string; language: string } } Now, trying to define the Form Input type like this: type FormInput = { id: keyof FormSchema | `${keyof FormSchema}.${string}` } Enc ...

Using Angular services in a lazily loaded module

There is a service named routing.service that subscribes to routing events and updates the Translate service when a parameter changes. The constructor code looks like this: this.router.events.subscribe(val => { if (val instanceof ActivationEnd ) { ...

Having trouble customizing the toolbar on ngx-quill? Quill seems to be having trouble importing modules

UPDATE: I jumped ship when I discovered that PrimeNg had a quill implementation, and since I was already using PrimeNg, I switched over. Initially had some issues, but upgrading to angular 7 and ngrx 7 beta resolved them. https://www.primefaces.org/primeng ...

Is it necessary to include explicit overlapping imports in Angular if they are already imported in the parent component?

Do you think the title needs clarification? Feel free to offer suggestions. I've noticed that my design components are ending up with a lot of imports. Some of these imports are duplicated in the component that is importing them. I'm managing to ...

Tips for preserving images while browsing a website built with Angular single-page application

Utilizing Angular's router for component navigation has been beneficial, but I am facing an issue with component reloads when going back. To address the problem of content reloading from the server, I have implemented a solution where the content arra ...

Dealing with null-safe operators issues has been a challenge for me, especially while working on my Mac using

Hey everyone! I'm encountering errors when using null sage operators in TypeScript. Can someone help me figure out how to solve this issue? By the way, I'm working on Visual Studio Code for Mac. https://i.stack.imgur.com/huCns.png ...

Error with Angular2+ Top Level Navigation Including both Parents and Children - activated route issue

Main Navigation Image My main navigation menu includes links with different parents, which are affected by the layout of each page: Home - /home Attractions - /site/attraction Animals - /site/animals Track Orders - /order/order-tracking Upload Orders - ...

The 'changes' parameter is inherently defined with an 'any' type.ts(7006)

Encountering an error and seeking help for resolution. Any assistance would be highly appreciated. Thank you. Receiving this TypeError in my code. How can I fix this issue? Your guidance is much appreciated. https://i.sstatic.net/cWJf4.png ...

Navigating TS errors when dealing with child components in Vue and Typescript

Recently, I encountered an issue where I created a custom class-based Vue component and wanted to access its methods and computed properties from a parent component. I found an example in the Vue Docs that seemed to address my problem (https://v2.vuejs.org ...

Can you explain the distinction between `any[]` and `{ [s: string]: any }`?

I was attempting to make this code snippet function properly: test(a: any[]) { let b: string[][] = []; b.push(Object.keys(a[0])); b.push(...a.map(e => Object.values(e))); } However, the compiler is throwing an error for the b.push(...a.ma ...

Tips for showing various tooltip text when iterating through a list?

I am currently working on a project where I am looping through a list and attempting to assign different tooltip text to various icons. However, I am struggling with the implementation. Here is a snippet of my code: <React.Fragment key={sv.key ...

Tips for testing Observable.fromEvent

Can you provide a method to test Observable.fromEvent using jasmine? @ViewChild('d') private inputDatePicker: NgbInputDatepicker; this.subscription = Observable.fromEvent(document, 'click').subscribe((event: KeyboardEvent) => { ...

The service functions are being called two times consecutively

I am utilizing an authentication component @Component({ selector: "oe-authentication-view", templateUrl: "./authentication-view.component.html" }) export class AuthenticationViewComponent implements OnInit { authorizationFormGroup: FormGroup; ...

What is the process to activate/deactivate a drop-down menu once a radio button has been chosen

JSON Data: radio1Data: any[] = [ { value: 'col-1', viewValue: 'Col-1' }, { value: 'col-2', viewValue: 'Col-2' } ]; radio2Data: any[] = [ { value: 'col-1', viewValue: 'Col-1' }, ...

How can you add or remove an item from an array of objects in Angular/RXJS using Observables?

Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step. NewObject.ts: export class NewObject { name: string; title: string; } Here's the example ...

The API call functions correctly on Node.js, but encounters issues when used on Angular or client-side JavaScript

Currently, I am attempting to connect to the STREAK Api using Angular. Strangely, when I send the request to Streak using Angular, a CORS Policy error is encountered. However, if I access the same request utilizing Node.js, the response is successful. Thi ...

Is there a way to remove a dynamically rendered component from a list?

Whenever I click a button, the same component is dynamically rendered on top of the list. But now, I need to implement a feature where users can delete any component from the list by clicking a cancel button associated with each component. Here's my ...

React | Utilizing ForwardedRefs with React Components

I'm currently working on a React project where I am creating a custom component that needs to be exported using forwardedRef. However, as I attempt to do this, an error keeps popping up: error This is the code snippet causing the issue: export inter ...

Deploying with Angular

My Angular application is functioning well without any errors. However, after deployment, I encounter a 404 error when reloading the page. I anticipate my app to work even after a full reload following deployment. Please see image for more details Any s ...