How can I transfer data between methods within Angular?

Help Needed: I have a service file with two methods, each having its own API. I want to call the getData method within the deleteData method. Can anyone guide me on how to achieve this?

.service.file
getData(): Promise<PagedResult<Sites>> {
    
    const url = `${environment.DATA_API_URL}/sites/GetSites`;
    console.log(url);
    return this.httpClient.get<PagedResult<Sites>>(url).toPromise().then((sites: PagedResult<Sites>) => {
      alert();
      console.log("sites: ",sites);
      });
  }

  deleteData(siteId: String): Observable<{}>{
      const url = `${environment.HELLO_API}/Data?siteId=`+ siteId;
      return this.httpClient.post(url, this.getSites)
      .pipe(
        catchError(this.handleError('deletSites'))
      );
  }
  
  .ts file
  
  async ngOnInit(){
     
      
      this.sites = await this.dataService.getData();
      console.log(this.data)
       
    }
  
  

Answer №1

My suggestion for you is to utilize Observable instead of Promises and incorporate Rxjs to concatenate, transform, and manipulate observables. It's best practice to avoid using "subscribe" in services.

As a result, your service can be structured as follows:

// Return an observable
getData(): Observable<PagedResult<Sites>> {

    const url = `${environment.DATA_API_URL}/sites/GetSites`;
    // This is a simple GET request
    return this.httpClient.get<PagedResult<Sites>>(url);
  }

  deleteData(siteId: String): Observable<{}>{
      const url = `${environment.HELLO_API}/Data?siteId=`+ siteId;
      return this.httpClient.post(url, this.getSites)
      .pipe(
        catchError(this.handleError('deletSites'))
      );
  }

With these changes, you are now able to work with observables in your component:

   ngOnInit(){
      this.sites = this.dataService.getData().subscribe(sites=>{
               console.log(sites);
          })
      )
    }
    delete()
    {
      this.sites = this.dataService.deleteData().pipe(
           switchMap(res=>{
               // Handle the response from the deletion operation
               // If you want to return the sites, do the following:
               return this.dataService.getData()
            })
      ).subscribe(sites=>{
               console.log(sites);
      }
     }

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

Error: JSON parse error - unexpected character 'a' at index 1

I'm encountering an issue while attempting to change the album title from "cars" to "car". The error message I keep receiving is: SyntaxError: Unexpected token a in JSON at position 1. Any ideas on what might be causing this problem? Below is the cu ...

Angular 2 Material 2 sleek top navigation bar

My toolbar is functional, however, there seems to be a gap around it instead of seamlessly blending at the top of the page. I also want it to be sticky, but I haven't figured out that part yet because it looks like my toolbar implementation is not co ...

Applying ngStyle based on changing information

I am struggling with setting the fill and stroke of an SVG path element based on the values in an array named shirts. <path class="st2" style="stroke-width:2.0;" [ngStyle]="myStyle(4)" d="M11.5,315....315.9z"/> In my code, I have defined a function ...

How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below: export enum XMPPElementName { state = "state", presence = "presence", iq = "iq", unreadCount = "uc", otherUserUnreadCount = "ouc", sequenc ...

Trigger a modal from one sibling Angular component to another

My application utilizes an Angular6 component architecture with the following components: <app-navbar></app-navbar> <app-dashboard></app-dashboard> The Dashboard component consists of: <app-meseros> </app-meseros> < ...

Posting data from an Angular 2 frontend to an Express server: A step-by-step

Seeking guidance as a beginner trying to understand the process of sending contact form data from Angular 2 to a Node/Express server. Currently, I have Angular 2 hosted on localhost:4200 and the express server running on localhost:3000. However, when attem ...

Guide on displaying and handling server-side validation errors within an angular form

I recently started working with Angular and encountered a problem I can't seem to solve. In my form, I need to display server validation errors from a Laravel REST API response. Although I can see the error message in the console, I'm unsure how ...

Is it possible to incorporate advanced transitions and animations using Angular 4?

Looking to incorporate animations using Angular 4 only. I have tried implementing the following advanced animation but struggled with writing parallel div animations in Angular 4. I believe this can be achieved via CSS, but unsure how to do so in Angular 4 ...

Tips for deploying an Angular application with Node.js

Currently, I've set up a nodejs backend by following a tutorial to integrate tweets into the frontend of my application. As I prepare to deploy to a development server, I have successfully built the frontend using ng build --prod. However, I am facin ...

Tips for conducting key down event testing on a material ui MenuList element utilizing react-testing-library

Looking to test the key down event on my MenuList component. Component: import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import * as React from 'react'; export default fu ...

On the subsequent iteration of the function, transfer a variable from the end of the function to the beginning within the same

Can a variable that is set at the end of a function be sent back to the same function in order to be used at the beginning of the next run? Function function1 { If(val1.id == 5){ Console.log(val1.id val1.name) } else{} Val1.id = 5 Val1.name = 'nam ...

Calculating the total of all values in a table

For my ngFor loop, the invoice total is calculated based on price and hours, but I also want to calculate the totals of all invoices in the end. <tr *ngFor="let invoice of invoiceItem.rows"> <td>{{ invoice.rowName }}</td> <td& ...

The TypeScript reflection system is unable to deduce the GraphQL type in this case. To resolve this issue, it is necessary to explicitly specify the type for the 'id' property of the 'Address'

import { ObjectType, ID, Int, Field } from 'type-graphql'; @ObjectType() export default class Address { @Field(type => ID) id: String; @Field() type: string; @Field() title: string; @Field() location: string; } More informa ...

Changing the dropdown value by clicking the previous and next buttons in Angular 2

I need to implement a feature in Angular 2 where the default date displayed in a dropdown is the current year. Additionally, when the "Prev" button is clicked, the selected year value in the dropdown should decrease by one. // Our root app component imp ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Error: The Turborepo package restricts the use of import statements outside of modules

I created a typescript "test" package in turborepo, which imports and exports typescript functions. Due to being in turborepo, it gets copied to node_modules/test. When attempting to run import {func} from "test", an error is thrown: SyntaxError: Cannot ...

Angular2's asynchronous data binding is still lagging even after the data has been successfully loaded

I have integrated Firebase with Angular2 to retrieve an object. import { Component, OnInit } from '@angular/core'; import { AngularFire, FirebaseObjectObservable } from 'angularfire2'; import { ActivatedRoute, Params } from '@angu ...

Steps for incorporating ProxyConfig in Angular7 Application1. First, create a new

Having trouble building the application with proxy configuration. It works fine with ng serve or npm run start, but I need it to work with npm run build or ng build. After that, I want to deploy the dist folder to Tomcat webapps and make everything functio ...

NPM is downloading an incorrect version of Angular (8.1.0)

After running the command "npm run ng --version", I see version 6.4.1 displayed. npm run ng --version However, when I run the command "npm install -g @angular/cli", it installs version 8.1.0 and generates an error. This is confusing to me. npm install - ...

Merging objects with identical keys into a single object within an array using Typescript

Here is the array that I am working with: Arr = [{ code: "code1", id: "14", count: 24}, {code: "code1", id: "14", count: 37}] My objective is to consolidate this into a new array like so: Arr = [{ code: "code1& ...