What is the process for unsubscribing through an HTTP post request within an Angular application

There is a POST API set up through API Gateway on AWS, but it seems to be returning an infinite loop of arrays, as shown in the image below. How can I make it return just one array?

Multiple requests

Below is the code snippet:

Angular

import { Component, OnInit, ViewChild, OnChanges, OnDestroy } from '@angular/core';
import { HttpClient } from '@common/http'; 
import { GetService } from '../get.service';
import { Observable, Subject } from 'rxjs';
import { IonSlides, IonSlide } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit   {
  protected ngUnsubscribe: Subject<> = new Subject<>();

constructor(public http:HttpClient) {}
  @ViewChild(IonSlides,{'static':false}) slides: IonSlides;

  slideOpts = {
    initialSlide: 1,
    speed: 400
 };
public result:any
public res:any
data:Observable<>;
ata:Observable<>;

ngOnInit(){
}

  getdata(){
    this.ata=this.http.post("XXXXXXXXXXXXXXXXXXXXXXXXX",{"freq":1});
    this.ata.subscribe(data=>{console.log(data)})

    return this.res
}

INDEX:any

slideChanged() {
    this.INDEX =this.slides.getActiveIndex().then(data=>console.log(data))
    return this.INDEX
}

HTML

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-toolbar>
</ion-header>
<p *ngFor="let a of getdata()">{{a}}</p>
<ion-card>
  <ion-card-content>
  <ion-slides  [options]="slideOpts" (ionSlideWillChange)="slideChanged()">
    <ion-slide>
        <h1></h1>
    </ion-slide>
  </ion-slides>
</ion-card-content>
</ion-card>

Answer №1

It is clear that the issue does not involve the API. This can be confirmed as you are utilizing Angular's HttpClient, which requires additional setup to handle multiple requests. The problem arises from your page being rendered multiple times while Angular's renderer is managing the layout.

The root of the problem can be traced back to this line of code:

<p *ngFor="let a of getdata()">{{a}}</p >

Each time this line is rendered, Angular invokes the getdata() function, triggering another request.

To resolve this issue, it's crucial to separate the result list from the function that requests it. Based on your code, it appears that data is an Observable. To address this, consider implementing the following:

<p *ngFor="let a of data | async">{{a}}</p>

Make sure to utilize the async pipe as shown above.

Refer to Angular's documentation

The async pipe subscribes to an Observable or Promise, returning the most recent value emitted. Upon receiving a new value, the async pipe triggers a check for changes in the component. When the component is destroyed, the async pipe unsubscribes automatically to prevent memory leaks.

Remember to call getdata() in an appropriate location, typically within the ngOnInit() method.

Additional tip: Managing responses from Observable subscriptions

If there is a need to receive only one response from an Observable subscription, you can achieve this by using the take operator.

import { take } from 'rxjs/operators';

[...]

someService.getObservable(...)
           .pipe( take(1) ) // <-- take first response
           .subscribe( (r) => { ... } );

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

How to retrieve nested JSON data with a unique row name in each API response

I am facing an issue where I am trying to fetch specific cryptocurrency data from the CoinMarketCap API. To do this, I have utilized a Kotlin data class file generated by the JSON plugin that corresponds to the API response. The CMC API returns data in the ...

The ReactDOM.createPortal modal has been successfully mounted onto the DOM, however, there seems to be no visible content

This project utilizes TypeScript and Next.js. Within it, there is a Modal component: interface ModalProps { onCancelModal: () => void; onAcceptModal: () => void; acceptEnabled: boolean; isLoading?: boolean; title: string; } const Modal: Re ...

"RxJS in Angular 2: The elusive map function seems to be missing

Issue: Received an error stating, "Property 'map' does not exist on type 'Observable'." import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; decl ...

Hermes, the js engine, encountered an issue where it was unable to access the property 'navigate' as it was undefined, resulting

Whenever I switch from the initial screen to the language selection screen, I encounter this error and have exhausted all possible solutions. I attempted to utilize "useNavigation" but still encountered errors, so I resorted to using this method instead. T ...

Ways to automatically display the Nebular Accordion using NgFor

Struggling with the latest Nebular version in Angular 7, I'm encountering a problem when using the nebular accordion component. Problem: The default behavior should have only one accordion expanded at a time, but setting expanded = true expands all of ...

Using Angular to implement conditional logic with ngSwitch

When the number is greater than 5, increase the font size to 50px using ngswitch in case. If the number is less than 2, set the font size to 15px. Unfortunately, I was unable to find a suitable syntax for this scenario, hence no code provided here. ...

The enigma of TypeScript

Whenever I try to declare or initialize data members in a class, the following methods never seem to work: var view: string[]; var view: string[] = []; let view: string[]; let view: string[] = []; Even though the TypeScript documentation states that it s ...

How to hide an item in Ionic 2 using navparams

Is there a way to dynamically hide or show a list item on page load depending on certain parameters? Here is an example of the code I am currently using: HTML <button ion-item (tap)="goToPage2()" [hidden]="shouldHide">Page 2</button> TS ex ...

Can you please clarify the purpose and functionality of @HostBinding(hostPropertyName)?

The @HostBinding() decorator requires an argument called 'hostPropertyName'. Are you familiar with this host and how can we discover its available properties? ...

What factors may be influencing the incorrect behavior of this simple code when using useState()?

In an attempt to replicate a problem I encountered in a larger project component, I have created a simple component. Let's consider the scenario where we have an arrayA and we want to add the value 1 to it on each button click, while also updating ano ...

When making Angular GET requests, the response may return a single Object instead of an Array

When making a GET request to my API, the data is returned as Objects inside an Object instead of an Array of Objects. This makes it difficult for me to iterate through and print the data. I am puzzled by why this specific request is behaving differently c ...

What is the mechanism behind making a Promise appear synchronous when using a Proxy in JavaScript?

const handler: ProxyHandler<any> = { get: (target: Promise<any>, prop: string, receiver: any) => { return target.then((o) => { return o[prop].apply(o); }); }, }; return new Proxy(obj, handler) ...

Exploring how to set dropdown menu width for Angular2 mat-select options

Currently, I am using the angular2 mat-select control and facing an issue with the width and position of its dropdown list menu. By default, it is wider and overflows the element on both sides by a few pixels. I have not found any option for adjusting the ...

What is the proper way to define the type when passing a function as a component prop, with or without parameters?

import { dehydrate, HydrationBoundary } from '@tanstack/react-query'; import getQueryClient from '@/lib/react-query/getQueryClient'; export async function RQBoundary<T>({ children, queryKey, fn, }: { children: React.Reac ...

Stop unauthorized access to specific pages on ionic platform unless the user is logged in

I have a scenario where I want to redirect users from the welcome page (welcome.page.ts) when they click on the login button. If they are already logged in, they should be redirected to the home page (home.page.html). Below is the code snippet from my welc ...

Tips for merging DTO (Data Transfer Object) with non-DTO objects

I'm currently working on a new endpoint and I need to validate only two parameters (limit and offset) with the dto. The third parameter is not supposed to be checked. My controller test code is not functioning as expected. When I try to use it, the e ...

The type 'Text' does not have a property named 'then'

Transitioning from .js to typescript. When I changed the file extension from .js to .ts while keeping the same code, I encountered an error stating Property 'then' does not exist on type 'Text'.ts in the then((value) method. The return ...

What are some strategies for distinguishing between callable and newable types?

I seem to be facing a challenge related to narrowing, specifically the differentiation between Fnc (callable) and Class (newable). The code snippet provided functions in Playground, but the autocomplete feature is lacking, as shown in the first image. My ...

Using TypeScript: Retrieve enum type value in type definition

I'm encountering an issue while attempting to define a specific type based on the value of an enum. enum E { A = "apple", B = "banana", C = "cherries" } // Defining the type EnumKey as 'A' | 'B ...

Showing Firebase messages in a NativeScript ListView in an asynchronous manner

I am currently struggling to display asynchronous messages in a ListView using data fetched from Firebase through the popular NativeScript Plugin. While I have successfully initialized, logged in, and received the messages, I'm facing challenges in ge ...