How come I am unable to terminate this Angular HTTP request?

I've been trying to implement a solution for canceling HTTP requests in AngularJS by referring to this Stack Overflow post. Here's the code snippet I'm using:

var canceller = $q.defer();

$timeout(function() {
  canceller.resolve();
  alert("HTTP request failed.");
}, 5000);

$http({
  url: endpoint + "/encode",
  timeout: canceller.promise,
  data: {
    post: posts.post[id]
  }
}).success(successFunction);

However, my console keeps showing an error message saying

ReferenceError: timeout is not defined
. What am I missing here?

Answer №1

Unfortunately, without a plunker example, it's challenging to reproduce the issue. However, I was able to successfully halt an HTTP request using your code as a reference. Check out the Plunker here

Modified Controller.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $q, $http, $timeout) {

  $scope.message = 'Operation not completed';

  var canceller = $q.defer();

  $scope.performAction = function() {
    $timeout(function() {
      canceller.resolve();
      $scope.message = "Action canceled";
    }, 1);

    $scope.message = "Action performed";
    var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
    var request = $http.get(url, { timeout: canceller.promise });
    request.success(function(results) {
      $scope.message = "Data loaded successfully";
      $scope.results = results;
    });
  }
});

view.html

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <p>{{message}}</p>
    <a href="" ng-click="performAction()">Perform action</a>
    <p>
      {{results}}
    </p>
  </body>

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

Utilizing React hooks to capture the checkbox value upon change and transfer it to the submitForm function

I've got a functioning hook that monitors the onChange event of input fields, then spreads them into a variable and sends them to a Lambda function for sending an email with SendGrid. Everything is working fine. However, when I add an input type of c ...

Code displayed on Facebook when sharing a website link implemented in JavaScript

Is there a way to prevent javascript code from appearing in Facebook posts when sharing links, whether it's done manually or through programming? I'm specifically looking for solutions to fix my website so that when I post links on Facebook, the ...

My ng-view html is unexpectedly displaying as plain string. What steps should I take to resolve this issue?

Why is my ng-view HTML displaying as plain text? How can I resolve this issue? I have encountered an error, here is the screenshot for reference: Unfortunately, I am unable to upload images at the moment. ...

Generate a fresh object with distinct identifiers

I am interested in creating a new object, utilizing unique keys consisting of comma-separated IDs. For instance, I have: const d = { "1,2,3,4,5,6,7,8,9,10": [ "created_by", "modified_on", "external_o ...

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

Access scope information when clicking with ng-click

I am currently using a php api to update my database, but I want the ability to choose which item gets updated with ng-click. app.controller('ReviewProductsController', function ($scope, $http) { $scope.hide_product = function () { ...

Displaying a component in a router view based on specific conditions

Currently, I am delving into the world of Vue3 as a newcomer to VueJS. In my project, there is an App.vue component that serves as the default for rendering all components. However, I have a Login.vue component and I want to exclude the section when rende ...

Maintaining the state of perspectives

I am currently working on an app that utilizes a form to filter objects from a database. Each change in the form triggers a request to the server for filtered objects, which are then displayed in another view. However, I have encountered an issue where the ...

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

Can you explain the distinct variations between these two approaches for obtaining API data?

When working with third-party APIs in NextJS 14, I encountered two different methods to query the API that resulted in slightly different outcomes. Method 1: Located within the /api folder as a route handler: export async function GET() { const res = aw ...

Having trouble accessing the value of an item in a dropdown box on a website

I am currently developing a webpage using HTML5 and Knockout Js. I am facing an issue where I am unable to retrieve the ID of the selected item from a dropdown box in order to insert a value into an SQL table. As an example, consider the following SQL tab ...

Stop user from navigating to specific route using React-router

I am currently utilizing react-router with history useQueries(createHashHistory)(), and I have a requirement to restrict navigation to certain routes based on the route's configuration. The route configuration looks like this: <Route path="/" name ...

The system encountered an error while trying to access the property 'enabled' of an undefined object

When working on a reactive form in my code, I need to ensure the values are properly set for the controls. ngDoCheck() { setControlValues(); } ngChanges(changes: SimpleChanges): void { setControlValues(); } private setControlValues() { try { ...

Leverage Dropzone functionality in combination with node.js

Just starting out with node.js and experimenting with file uploads using drag and drop. Initially, I created a basic uploader without drag and drop functionality: var http = require('http'); var formidable = require('formidable'); ...

Issue with AngularJS directives - encountering a problem with the property 'compile' being undefined

Just starting out with AngularJS and attempting to make a basic directive. Unfortunately, the code is throwing a TypeError: Cannot read property 'compile' of undefined. Any advice or suggestions would be greatly welcomed. JS var xx = angular.mo ...

There is no information available at this time

Currently, I am delving into Angular and am keen on creating a web application that consumes a Restful Web service. The setup of my page is as follows: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html ng-app="Tri ...

Locate elements based on an array input in Mongoose

Define the Model: UserSchema = new Schema({ email: String, erp_user_id:String, isActive: { type: Boolean, 'default': true }, createdAt: { type: Date, 'default': Date.now } }); module.export ...

Exploring the Differences Between Next.js Script Components and Regular Script Tags with async and defer Attributes

Can you explain the distinctions between the next js <Script /> component rendering strategies such as afterInteracive, beforeInteractive, and lazyLoad, as opposed to utilizing a standard <script /> tag with attributes like async and defer? ...

Steps to extract date selection from a datepicker using jQuery

I recently implemented this code snippet to utilize datepicker for displaying dates: $(document).ready(function(){ $("#txtFrom").datepicker({ numberOfMonths: 1, onSelect: function (selected) { var dt = new Date(selected); ...

Iterating through elements to set the width of a container

I am currently working on a function that dynamically adjusts the width of an element using JavaScript. Here is my JavaScript code: <script> $('.progress-fill span').each(function(){ var percent = $(this).html(); if(per ...