Angular2 - The 'then' property is missing from the 'void' type

In my attempt to create a simple app, I encountered an issue when trying to delete a user by clicking on the delete button.

When attempting to run the server, I received an error related to the then method in the deleteUser() component:

 deleteUser(user: User, event: any) {
    event.stopPropagation();
    this.userService
      .deleteUser(user)
      .then(res => {
        this.httpUsers = this.httpUsers.filter(h => h !== user);
        if (this.selectedUser === user) { this.selectedUser = null; }
      })
      .catch(error => this.error = error);
  }

The service looks like this:

  deleteUser(user: User) {
    console.log('Deleting user');
  }

The error message reads:

app/users.component.ts(46,8): error TS2339: Property 'then' does not exist on type 'void'.

The error occurs on line 46 with .then(res => {

After researching online, I came across this question and attempted to remove void from the deleteUser function, but it did not resolve the issue.

Can anyone provide insight into what I might be doing wrong?

Answer №1

In order to delete an item, you need to invoke the delete function to receive a promise which can be followed by using .then( in this manner:

removeUser(user: User) {
   return this.http.delete(url+id,...).toPromise();
}

Answer №2

If you're working with promises, then the 'then' method is the way to go. On the other hand, if you need to make a call to a REST API and map the result, using 'subscribe' would be more appropriate.

Implementing 'then'

Service method

  getAudits() {
    // console.log('audits' + amplify.store('audits'));
    let audits: Audit[] = amplify.store('audits'));    
    return Promise.resolve(audits);
  }

Component

this.auditService.getAudits().then(audits => {
  this.audits = audits;
  this.updateChart(true);
});

Implementing 'subscribe'

Service method

  getAudits() {
    return this.http.get('/rest/batch').map(res => res.json());
  }

Component

this.auditService.getAudits().subscribe(audits => {
  this.audits = audits;
  this.updateChart(true);
});

Answer №3

Your service's deleteUser method does not have a return value of type Promise, which is why you cannot chain .then(res => ...) after it as mentioned in the error message.

deleteUser(user: User) {
  console.log('Deleting user'); // <-- no explicit return statement - defaults to void
}

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

Show information stored in Angularjs2 file (.ts) within an HTML document

Here is the code snippet from my .ts file: constructor( private config : ConfigService, private http: Http){ this.getWS('ngoName') .do((data) => { console.log(data); this.saveObj(data); }).to ...

Visuals failing to display following Angular project compilation

After completing the coding for my app, I attempted to put it into production mode and after testing, I noticed that the images were not displaying as the logo in the app. However, in development mode, everything seems to be working fine. This is the struc ...

Is there a way to automatically scroll to the bottom of a div when it first

Looking to enhance my application with a chat feature that automatically scrolls to the bottom of the chat page to display the latest messages. Utilizing VueJs: <template> <div id="app"> <div class="comments" ...

The 'ngForOf' directive cannot be bound to 'div' element as it is not recognized as a valid property

Encountering an issue with adding an ngFor directive on a div, which is causing a warning and preventing my HTML from rendering properly. I experimented with using *ngFor on various elements like <li>, <tr>, and <span>, but kept getting ...

There is an error in the test due to the undefined injected service in the service

While working with my code, I encountered an issue where I injected a service in the constructor using ServiceLocator.injector. During Unit Testing, I received an error message stating "TypeError: Cannot read 'environmentWeb' of undefined". The m ...

Process running on an undetermined outcome (resulting from a function that requires promises to be fulfilled)

I'm feeling pretty lost when it comes to handling promises. I've been doing a lot of reading, particularly in the context of Typescript and Angular, as I'm working on fetching data from an API REST. Within my code, there's a method call ...

Need help with TypeScript syntax for concatenating strings?

Can you explain the functionality of this TypeScript syntax? export interface Config { readonly name: string readonly buildPath: (data?: Data) => string readonly group: string } export interface Data { id: number account: string group: 'a&a ...

The TypeScript library React-Time-Ago seems to require a number, but I'm passing it a string instead. I'm struggling to find a way to make it accept a number

import ReactTimeAgo from "react-time-ago" <ReactTimeAgo date = {tweet._createdAt} /> _createdAt displays time in the format 2022-06-02T01:16:40Z To convert this into a more human-readable form like " ...

Extract headers from an HTTP GET request in Angular

Currently, I am working on a project that involves making API calls to retrieve blob data. The backend also sends the file name in the header, which is causing some issues for me as I am unable to access the header from the API response. Below is my code ...

The data type '{}' cannot be assigned to the data type 'Profile'

I recently started using TypeScript and encountered this error: Type '{}' is not assignable to type 'Profile'. within the context of this.profile. Can anyone suggest a solution? import { Component } from '@angular/core'; ...

Activate the button when a checkbox within a looping structure is selected using Angular 5

As a relatively new Angular 5 user, I am working with a button that looks like this: <button *ngIf="type!='invoices' && this.action==='edit'" disabled (click)="genera(fields.termini)" class="ml-16 mat-raised-button mat-accen ...

Angular element in a child window of a browser

Is it possible to create a new child window from an Angular application and display a predefined Angular component in it? Note: I am specifically seeking a solution that does not involve a modal dialog. ...

Svelte with Typescript: Uncovering the Types of Props

Issue: I am trying to create a function that can take a component as the first argument and its props as the second argument in a generic manner import Modal from "./Modal.svelte"; function openModal(component: typeof Modal, componentProps: ...

Managing forms in Django rest framework and Angular2

I am currently working on a project in which my Rest API is built using django rest framework to serve JSON, while my frontend is completely separate. The frontend is a standalone project created through yeoman and could potentially be an Ionic app or an A ...

What is preventing TypeScript from automatically inferring the type of an argument in a generic function that utilizes `keyof`?

What causes the error in this code snippet? type MyType = { a: string, b: string } function cantInfer<In, Out>(fn: (i: In) => Out, i: In) { } function myFunction<K extends keyof MyType>(key: K): string { return ''; } ...

Unable to disable the rule explicit-function-return-type in ESLint while performing TypeScript linting

I am currently utilizing: ESLint version 7.5.0 - operating through the command line for Angular files TypeScript-eslint/eslint-plugin version 3.7.0 TypeScript-eslint/parser version 3.7.0. Despite having the rule '@typescript-eslint/explicit-function- ...

The Angular 10 HTTP request interval is not functioning as expected

I am currently working on Angular 10 and implementing a feature that checks connectivity by sending a request to the server every 5 seconds. The issue I'm facing is that the request does not seem to be sent out; instead, it just logs a console.warn m ...

Is it possible for an Angular2 HTTP request to retrieve the response body as binary data?

I'm facing an issue with a URL that returns HTML content with charset=iso-8859-7. Angular's HTTP request converts the data to utf8 by default, making it difficult for me to encode them back in iso-8859-7 properly. Upon researching, I discovered t ...

Using Typescript and React to retrieve the type of a variable based on its defined type

Just getting started with Typescript and could use some guidance. Currently, I'm using React to develop a table component with the help of this library: Let's say there's a service that retrieves data: const { data, error, loading, refetc ...

Accessing User Session with NextAuth in Application Router API Route

Utilizing NextAuth in conjunction with Next.js's App Router, I have established an API route within my /app/api directory. Despite my efforts, I am encountering difficulties retrieving the session associated with the incoming request. Below is the sn ...