Obtain the API response using a Promise.then() in AngularJS

Recently, I've been delving into AngularJS and trying to create a function that deletes a user. The goal is to have the function return a boolean value indicating whether the deletion was successful or not.

Despite my best efforts, the promise always resolves to true even when the API response indicates failure. I followed advice from various sources like this one: Return value from a promise in Angular, but couldn't find a solution.

In my user controller file (user.controller.js), the code looks like this:

deleteUser(user) {

    const self = this;

    self.userActionPromise = self.userService.deleteUser(user.id).then(deleted => {
        if (deleted) {
            self.messagesService.successMessage('user.DELETE_SUCCESS');
            self.loadUsers();
        } else {
            self.messagesService.errorMessage('user.DELETE_FAILURE');
        }
    });
}

And in my user REST service file (user.rest.service.js), here's what it contains:

self.user = $resource(config.restServerUrl + 'users/:id', {id: '@id'}, {
    delete: {method: 'DELETE'}
});

deleteUser(id) {
    return this.user.delete({id: id}).$promise.then(deleted => {
        return !!deleted;
    });
}

Answer №1

outcome:

execution of this.user.delete({id: id}).$promise.then(deleted => {
  return !!deleted;
})

always guarantees a true response upon completion of the request.

If you wish to handle potential failures:

execution of this.user.delete({id: id}).$promise.then(deleted => {
  return deleted;
}, function (error) {
  return error;
})

The second function will be triggered in case the server returns an error

If there is an error, the HTTP response status code should reflect it, such as 500 (https://developer.yahoo.com/social/rest_api_guide/http-response-codes.html). When returning a status code of 200 with a result of false, it simply informs AngularJS that the request was successful and the outcome was false

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

The command "npm run build:css " is not functioning properly, but when I execute the script independently, it works fine

Recently, while working on a program using npm script on my Mac system, I encountered some issues. Despite having installed node-sass globally, running "npm run build:css" did not work as expected. The content of my package.json file can be viewed here. Th ...

Navigate through the website by transforming the arrow and clicking the link

I am struggling with transitioning my arrow from › (right) to ˇ (down) when toggled. I can't figure out where to place it. If you look at Menu 1 > Submenu 1 > Text with hyperlink I want the 'Text with Hyperlink' to be clickable on ...

EMFILE error encountered while attempting to initialize a new react-native project and watch file changes

Looking to start a new react-native project? Here are the steps: Begin with react-native init testproject then run react-native run-ios Encountering an error while watching files for changes: EMFILE {"code":"EMFILE","errno":"EMFILE","syscall":"Error watc ...

Bidirectional data binding in Vue.js enables seamless communication between parent and child components, allowing for dynamic

Trying to implement v-for and v-model for two-way data binding in input forms. Looking to generate child components dynamically, but the parent's data object is not updating as expected. Here's how my template is structured: <div class="cont ...

Create a sleek and dynamic navbar effect with Bootstrap 5 by easily hiding or showing it after scrolling

Is there a way to make the Bootstrap navbar hide after scrolling for 300px? I found a code snippet here that hides the navbar on scroll, but it hides immediately. How can I modify it to hide only after scrolling 300px? HTML: <nav class="autohide ...

Error message encountered: 'GlobalStyles' is not a valid export from the module '@material-ui/system' (referenced as 'SystemGlobalStyles')

./node_modules/@material-ui/core/GlobalStyles/GlobalStyles.js Error encountered while trying to import: 'GlobalStyles' is not exported from '@material-ui/system' (imported as 'SystemGlobalStyles'). I am currently grappling wi ...

Generate HTML table with CSS dynamically applied through jQuery

After performing some calculations and applying CSS rules using the .css() function in jQuery to color the background of a table, I am facing an issue when trying to print the page. The printed page appears in black and white without retaining any styling ...

Unable to activate the 'Click' function in Angular/Typescript after selecting element with 'document.querySelector'

In my Angular 8 Project, there is an element on a page with a unique string attached to the attribute 'data-convo-id'. This element has a click function that loads data based on the data attribute specified above. However, without direct access ...

Get a confirmation from Ajax, PHP, and Mysql after successfully inserting data

Here is my AJAX call to submit a form to a MySQL database using a PHP file on a server: <script type"text/javascript"> $(document).ready(function(){ $("form#submit").submit(function() { // storing form values and sending via AJAX var fn ...

Expanding Module Scope to Just the Request (employing Require, Node.js)

Original Query The project I am currently working on is using Express to manage HTTP requests. The structure of the project is quite intricate, with multiple embedded require statements. Our main challenge lies in maintaining access to the request and re ...

Counting consecutive sentences starting with "The" using Javascript

As a newcomer, I am attempting to create a code that can split a copied text into sentences and then identify if three or more consecutive sentences begin with the word "The". My goal is for the program to be flexible regardless of the number of sentence ...

When trying to link a Redis microservice with NestJS, the application becomes unresponsive

I am attempting to create a basic hybrid app following the guidance provided by Nest's documentation, but I have run into an issue where the app becomes unresponsive without any errors being thrown. main.ts import { NestFactory } from '@nestjs/c ...

What steps should be taken to activate an event when an object is reorganized?

As I work on enhancing a website that is not my own, I encounter a table filled with values. To improve this site, I have created a jQuery script to scrape the values from the table, add a column, and calculate a specific value for each row. However, as us ...

What is the best way to define coordinates or set margins for the autoTable component in jsPdf when using React js?

While working with the jsPdf library to create a PDF in React, I am encountering an issue where I am unable to set margins for the autoTable when there are multiple tables on a single page. Below is the code snippet: import React from "react"; ...

What is the best way to use jQuery for creating a downloadable JSON file that can be used for saving game data?

Is there a way to create a 'save game file' using Jquery or JavaScript? I know you can use HTML's local files in the browser, but I want users to be able to click a 'save' button and choose a location to download their generated ga ...

What is the best way to modify the class of my <li> element with JavaScript?

My asp.net project utilizes a master page that includes a list within it. <ul id="navigation"> <li id="li1" runat="server" class="selected"><a href="Events.aspx">Events</a></li> <li id="li2" runat="server ...

What is the process for activating the currently active tab or link within the MDBNav component of MDBreact?

Here is the code snippet I am working with: import React from "react"; import { BrowserRouter } from 'react-router-dom'; import { MDBNav, MDBNavItem, MDBNavLink } from "mdbreact"; const CustomTabs = props => { return ( <BrowserRouter& ...

When a new marker is clicked on Google Maps, the previous Infowindow will automatically close

Here are some specific locations to consider: var places = [{ "id": 1, "ReferenceNumber": "52525252525", "Address" : "School" , "Latitude": "21.585486", "Longitude": & ...

Tips for troubleshooting objects within an Angular template in an HTML file

When I'm creating a template, I embed some Angular code within my HTML elements: <button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon" ng-if="(!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'curren ...

Using v-bind:class to assign an object value

I have a Vue component that displays an image grid. I want users to be able to select an image by clicking on it. When an image is selected, its style should change, and if clicked again, it should return to its unselected state. I am trying to bind the & ...