The error message TS2339 in Angular service.component indicates that the property 'subscribe' is not recognized on the type 'Promise<Object>'

Currently, I am in the process of learning Angular by developing a web application for my parish. I have implemented a method for deleting items in the products-list.component.ts file which appears to be technically correct. However, when I attempt to run npm start, an error occurs with the following code:

TS2339: Property 'subscribe' does not exist on type 'Promise'.

I apologize if my description of the issue does not adhere to the formal guidelines, as I am relatively new to this field and might not be articulating the problem accurately. Thank you for your understanding.

The specific error is arising within the onDelete method.

In other classes where similar code is used, I have not encountered this particular error before. Could there be any missing imports in the list.component-products?

import { Component, OnInit, SystemJsNgModuleLoader } from '@angular/core';
import { NgForm } from '@angular/forms';


import { Prodotti } from 'src/app/model/prodotti.model';
import { Router, ActivatedRoute } from '@angular/router';
import { JsonPipe } from '@angular/common';

import { ProdottiListService} from 'src/app/features/prodotti/components/prodotti-list/prodotti-list.service';
import { ToastrService } from 'ngx-toastr';



let Header_Msg = "Gestione Prodotti";


@Component({
  selector: 'app-prodotti-list',
  templateUrl: './prodotti-list.component.html',
  styleUrls: ['./prodotti-list.component.css']
})
export class ProdottiListComponent implements OnInit {

  constructor(private service: ProdottiListService, private toastr: ToastrService) {

   }

  ngOnInit() {
    this.service.refreshList();
  }

  populateForm(emp: Prodotti) {
    this.service.formData = Object.assign({}, emp);
  }

  onDelete(id: number) {

    if (confirm('Confermi la cancellazione del Record ?'))  {
        this.service.deleteProdotti(id).subscribe(res => {
          this.service.refreshList();
          this.toastr.warning('Cancellazione eseguita con successo', Header_Msg);
        })
    }
  }

}

ERROR in src/app/features/prodotti/components/prodotti-list/prodotti-list.component.ts(41,4): error TS2339: Property 'subscribe' does not exist on type 'Promise'.

Answer №1

It is crucial to ensure that the function returns an Observable instead of a promise.

For instance, if you look at the ProductListService, the method deleteProducts currently returns a promise. Therefore, you should be using .then(..) rather than .subscribe().

To resolve this issue, either modify your service function to return an observable, or refrain from using .subscribe in the component:

this.service.deleteProducts(id).then(res => {
          this.service.refreshList();
          this.toastr.warning('Deletion completed successfully', Header_Msg);
        })

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 causes observables stream to be cancelled or stopped by my HTTP request?

I am facing an issue with adding a new property called Blobs to each application in an array of applications. I need to make a separate HTTP request to fetch Blobs for each application using the switchMap operator. However, the problem is that only the las ...

Access the JSON data containing sub array values and showcase them on an HTML page by utilizing ngFor

Greetings! I am currently working on a web application where I need to showcase student data that is being received in JSON format. Below is the TypeScript code snippet that outlines the structure of the student data: export interface studentData{ ...

Unable to play audio src in Angular 2 due to http request issue

The data I gathered and included in the audio source is not playing. component.detail.ts export class DetailComponent implements OnInit { @Input() detailName: string; @Output("playnhac") play = new EventEmitter(); private mp3Link:string; ...

Angular: displaying dates in a specific format while disregarding time zones

Is there a way to format date-time in Angular using DatePipe.format() without converting timezones, regardless of location? For instance, for various examples worldwide (ignoring time differences) I would like to obtain 07/06/2022: console.log('2022-0 ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

The error being thrown at line 538 in the module.js file is causing issues when using

I encountered an error in my Angular 4 project that says "module.js:538 throw err;". Can anyone provide insight on what this means? module.js:538 throw err; ^ Error: Cannot find module 'swagger-js-codegen' at Function.Module._resolveFilena ...

Creating a dynamic return statement in typescript: A step-by-step guide

I am looking to dynamically set a return value to a variable based on values retrieved from an API. The current function in question uses static values: this.markDisabled = (date: NgbDate) => { return (this.calendar.getWeekday(date) !== 5 && ...

Running a function exclusively within a single div using Angular 2

I am currently using *ngFor to group items, and it's functioning correctly. However, I am having trouble displaying the "listofGroup" in the view even though it works in the console. Specifically, I need to run a function within a specific div in Angu ...

Comparing dates in Angular 6 can be done by using a simple

Just starting with angular 6, I have a task of comparing two date inputs and finding the greatest one. input 1 : 2018-12-29T00:00:00 input 2 : Mon Dec 31 2018 00:00:00 GMT+0530 (India Standard Time) The input 1 is retrieved from MSSQL database and the in ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...

Injecting data into mat-dialog-actions in Angular - how can it be done?

I have a question regarding passing data to a method in Angular. Below is the code snippet: Is there a way to pass data into addNpi() similar to how editNpi(data) is done below? Your help is appreciated. Thank you! <mat-dialog-content> <ip-dat ...

Get your hands on a complimentary Angular 2 scheduling tool

I am in need of integrating a scheduler into my angular 2 application. My goal is to schedule various employees within a day view and I found two paid components that might work for me: FullCalendar Scheduler Demo Bryntum Angular 2 Scheduler Currently, ...

Angular 2 router generates incorrect URLpaths

When navigating through my routes, I encountered an issue with the following routing setup: const routes: Routes = [ { path: '', component : HomeComponent, children: [] }, { path: 'login', ...

Utilizing a React npm component within an Angular project: A step-by-step guide

After successfully creating a simple react component and publishing it to the NPM registry, I encountered an issue when trying to use the same plugin in an Angular project. The custom plugin can be found at: https://www.npmjs.com/package/reactcustomplugin ...

Exploring how enums can be utilized to store categories in Angular applications

My application has enums for category names on both the back- and front-end: export enum CategoryEnum { All = 'All', Category1 = 'Category1', Category2 = 'Category2', Category3 = 'Category3', Cate ...

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

Utilizing Angular for enhanced search functionality by sending multiple query parameters

I'm currently facing an issue with setting up a search functionality for the data obtained from an API. The data is being displayed in an Angular Material table, and I have 8 different inputs that serve as filters. Is there a way to add one or more s ...

Iterating through an array with ngFor to display each item based on its index

I'm working with an ngFor loop that iterates through a list of objects known as configs and displays data for each object. In addition to the configs list, I have an array in my TypeScript file that I want to include in the display. This array always ...

Leveraging Angular 6: Implementing custom scripts on a component basis and verifying their presence

I need some help with a script that I want to run on a specific component only. I've managed to add the script to the component, but there are a few issues that I'm unsure how to fix. When I go to the component, the script is added to the DOM b ...

The failure of an Angular2 HTTP GET request with a header

Attempting to make a simple get request using angular2 http, like this: (including the token retrieved from a post to my api) let idToken = localStorage.getItem('id_token'); let authHeader = new Headers(); if (idToken) { authHeader.append(&a ...