What is the best way to transfer values between various methods within a single service file in Angular?

In my service file, I have two methods called getData and delete. The data is sourced from an API and the getData method works fine.

However, I am facing a problem with the delete() method where siteId is not being read correctly. When I click the save button, it should be able to identify the siteId and delete the relevant data. I suspect that there might be an issue with how I've implemented the code in both the service file and component file.

This is what my service.ts file looks like:

datasites : Data
getData(): Promise<PagedResult<data>> {

  const url = `${environment.API_URL}/data/GetData`;
  
  return this.httpClient.get<PagedResult<data>>(url).toPromise();
}
delete(): Promise<Data>{
  alert(2);
  const siteId = this.datasites.principalId;
  const url = `${environment.ADMIN_API_URL}/sites/DeleteSite?siteId=`+ siteId;
  
  console.log(siteId);
  return this.httpClient.post<Sites>(url, request).toPromise();

}

And here is the component.ts file:

async ngOnInit(){
      alert("***********");

      this.data = await this.dataService.getData();
      
      console.log(this.data[0].principalId);
       this.deleteSiteId = this.data[0].principalId;
       
       console.log(this.deleteSiteId);

    }
   delete(data){
     alert(aaaaaaaaa);
     this.dataService.delete(data);
     console.log(data.principalId);

   }
    showButtons: boolean = false;
  clickEvent(data){
    data.isClicked = !data.isClicked;
    this.showButtons = !data.showButtons;
  }

And finally, the .html file:

<div *ngIf="showButtons">
      <button (click)="delete()">Save</button>
    </div>

Answer №1

Your code has several issues that are quite evident to me.

One major issue is the absence of a linter in your editor, which would have helped identify the problem easily. ;)

In addition, you're invoking the delete() method in your component.ts file without passing any parameters, which it requires.

Similarly, in your service.ts file, you are making the same mistake but in reverse. Ha!

If possible, try reproducing the mentioned problem on a platform like StackBlitz for better understanding.

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

Ways to guarantee that a link is deactivated upon page load

I'm facing two issues Here is the markup for the link: <a href="/Home/DisplaySpreadSheetData" id="displaySpreadSheetLink">DisplaySpreadsheetData</a> 1) I'm trying to disable the link by default under document.ready ...

Eliminate attributes from an object that are not defined within a specific type interface

I am trying to filter out properties from an object that are not defined in a specific type interface. Suppose I have the following interface: export interface CreateCustomerUserInput { fullname: string; email: string; } And this is my initial o ...

Encountering a Typescript error while attempting to convert a JavaScript file to Typescript within an Express

After deciding to transition my express.js code to typescript, I have encountered an issue with my user model. Below is a simplified version of the code: //user.model.ts import { Schema, Types } from 'mongoose'; export interface User { na ...

Printing the contents of a datatable in HTML can be achieved in VB.NET by including headers and setting paper orientation, fit to page, and grand total for print preview and direct print

I'm attempting to print the contents of a datatable in HTML for print preview and direct printing, including headers, setting paper size, orientation, and fitting to page in VB.NET. While it may be easy to accomplish this using an rdlc report, I am u ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...

Masonry style attempted for posts but did not produce desired outcome

I've been experimenting with different methods to achieve a masonry style layout for my posts. So far, using float:left seems to work almost perfectly, but occasionally there are gaps between the posts. I'm on the lookout for a solid solution to ...

Conceal the choice when aria-expand is in a deactivated state

I'm currently facing a challenge with hiding an option in mat-select only when aria-expanded is false. In the dropdown menu, I have both "Select All" and "Deselect All" options. However, when the menu is closed, it displays "Deselect All" by default ...

Typescript's spellbinding courses

I'm encountering some issues with Typescript and the "@botstan/Magic" library in nodejs. Before we proceed, please take a look at the "Magic" documentation. Follow these lines: import Magic from "@botstan/magic"; import * as _ from "lodash"; @ ...

What could be causing the interface to malfunction when defining a type that includes an enum as a property key?

When dealing with an enum and wanting to use its values as keys in objects, the type declaration looks like this: enum Bar { A, B } let dictionary: BarDictType = { [Bar.A]: "foo", [Bar.B]: "bar" } type BarDictType = { ...

Beginner in CSS Structuring

Hey there, I'm facing a bit of a challenge and could really use some guidance. I'm trying to design a layout for a website with specific components, but I can't seem to achieve the exact look I want. I know it should be straightforward, but ...

Adding a method to an object with TypeScript: A step-by-step guide

In my current scenario, I am faced with a challenge where I need to test a function with a specific use of this. However, typescript poses constraints by either disallowing me from adding the method to the object, or if I define it as any, then my interfac ...

Issue with organizing columns in Plotly-Dash using personalized CSS

I expected the code below to create three adjacent drop-down menus under a tab labeled Setup, but I'm actually seeing them stacked on top of each other. What mistake am I making? Any guidance would be highly appreciated! I've provided the releva ...

HTML: Mark the chosen hyperlink or tag

In my HTML page, I am looking to keep the link selected when it is clicked on. Here is the initial HTML code: <table class="main-dev"> <tr> <td> <a class='titleForm' style="cursor:pointer"> ...

Facing issues with the template URL not functioning properly during the migration from Angular 1.5 to Angular 6

I am currently in the process of migrating an Angular 1.5 project to Angular 6, but I've encountered an issue with the templateUrl not working in the Angular 1.5 component. The packages I am using are: Angular CLI 6.0.8 TypeScript 2.7.2 Angular 6.0.7 ...

Populate a <div> element with text and an <input> field

Is there a way to automatically adjust the size of an input element inside a <div> when the <div> is resized? I've been trying to figure it out for the past 2 hours and I'm just not getting it. ...

Angular 5 encountering issue with @Injectable annotation causing TypeScript error

While trying to compile my code, I encountered the following error: import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class TaskService { constructor(private http: Ht ...

Guide to incorporating d.ts file for enhancing intellisense in VS Code using a method akin to the NPM approach

In my nodejs project (in JS), I find myself relying heavily on node global variables. Despite receiving warnings against using globals, everything works well except for one thing: The lack of intellisense for globals. Every time I need to use a global fu ...

Nested Flexbox Elements

Looking to nest elements using flexbox in order to achieve the following layout: https://i.sstatic.net/bEKps.png Does anyone know how to make this happen? ...

Currently in the process of optimizing controllers but continuously encountering 404 errors when making api requests

I previously utilized the SampleData controller that is automatically generated. I added my custom methods, everything was functioning perfectly. Recently, I decided to create a new class for better organization purposes. After pasting in the desired metho ...

Angular: Dividing a web page with its individual controller

Exploring Angular Composition An individual new to Angular is eager to implement the concept of "composition," where the main page contains various smaller web page components. Starting off with just a Header section that binds perfectly. <html> &l ...