How to inject a variable into an AngularJS service that utilizes both $http and $interval functions?

Struggling with $http and $interval, I stumbled upon this code.

http://embed.plnkr.co/fSIm8B/script.js

I forked it here: http://plnkr.co/edit/Al8veEgvESYA0rhKLn1q

To make it more functional, how can I pass a variable to the service?

Here is the broken code:

var myAppModule = angular.module("myApp", ['ngMockE2E']);

myAppModule.controller('MyController', function($scope, pollingService) {

var stopNow = 5;
var id = 1001;

pollingService(stopNow, id).then(
function(value) {
  //fully resolved (successCallback)
  $scope.data = value;
  console.log('Success Called!');
},
function(reason) {
  //error (errorCallback)
  console.log('Error:' + reason);
},
function(value) {
  //notify (notifyCallback)
  $scope.data = value;
  console.log('Notify Calls:' + value.count);
}
);

});

myAppModule.factory("pollingService", function ($http, $interval, $q, $httpBackend) {

var data = { resp: {}, status: 'Initialized', count: 0};
var deferred = $q.defer();

$httpBackend.whenGET("data.json").respond({type:'mock'});

//just loop 10 times for an example
var completed = $interval(function(ip) {
data.status = 'Running';

**//How can I Change the $http URL by passing a variable in?**
$http.get('/getId/' + id).then(function(r) {
  data.resp = r.data.type;
  data.count++;
  **//Instead of 5 I want to pass this in as an variable**
  if (data.count==stopNow)
  {
    $interval.cancel(completed);
  }
  console.log('Http\'s:' + data.count);
  deferred.notify(data);
});
}, 500, 10);

completed.then(function(){
data.status = 'Completed!';
deferred.resolve(data); 
});

return deferred.promise;
});

Answer №1

If you want to include a function in your service, you can do the following:

myAppModule.factory("fetchDataService", function ($http, $interval, $q, $httpBackend) {

return {
      fetchData: function(param1, param2){
        // Add your custom code here
        return deferred.promise;
     }
}

Next, in your controller:

fetchDataService.fetchData(param1, param2).then(...)

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

"Cordova's keyboard seems to have a mind of its own, popping up

Currently developing an app using the Ionic framework with AngularJS that involves many forms. Whenever I open a form page, the keyboard automatically opens. I have implemented the Ionic keyboard and added the following preference: <preference name="Ke ...

Error: Failed to find the location because geolocate has not been defined

I searched extensively online for a solution to my problem without success, so I am reaching out to seek your assistance. I am attempting to utilize the Google Address auto-complete API within an asp.net core framework. In my razor file, I have included: ...

Creating a square shape in Twitter Bootstrap to frame an item on a webpage

I've been working on creating a webpage that looks similar to the image provided. I've managed to get about 90% of it done, but there are a couple of issues I'm facing: How can I create a square with a triangle at the bottom as shown in th ...

Zod vow denial: ZodError consistently delivers an empty array

My goal is to validate data received from the backend following a specific TypeScript structure. export interface Booking { locationId: string; bookingId: number; spotId: string; from: string; to: string; status: "pending" | "con ...

Issue with Jquery 1.10.2 not functioning properly on IE10 with JSON data

I am currently experiencing difficulties with parsing JSON data. The following function is causing errors: parseJSON: function( data ) { //Try to parse using the native JSON parser first if (window.JSON && window.JSON.parse) { retu ...

Using form submission to implement reCAPTCHA v3 in g-recaptcha

Is the Recaptcha API causing trouble? I have the key on both the submit button and the form tag, but it's only sending the sitekey without generating tokens. Any suggestions are welcome. You can either use the key in the form tag: <form method=&qu ...

What's causing ng-show to malfunction in IE11 on AngularJS?

I am experiencing a strange issue with my code - ng-show works perfectly fine on Firefox, but not on IE 11. <div ng-show="isExist" class="panel panel-default"> Here is the relevant code snippet from the controller: $scope.isExist = false; if(user ...

Is there a way to modify the background color of ::before when hovering over it?

I have a ul-li list and when i hover last li ::before element looks white and not so good. I want to change it when i hover the last li element. How can I achieve this? Here are my codes: <div className="dropup-content"> <ul> & ...

Errors are being displayed in the console when attempting to use Vuex getters in a component. This is happening because the Vuex state properties are still null at the time the getters

When assigning results from GET requests to my Vuex state properties, it's expected that they won't be available instantly. However, I have a getter like the following: findChampion: (state) => (id) => { let championId = id.toString() ...

Click to shift the div downwards

Currently, I have a piece of javascript applied to a div that directs the user to a specific link: <div style="cursor:pointer;" onclick="location.href='http://www.test.com';"> I am wondering if there is a way to add an effect where, upon ...

Is it possible to redirect to the initial request after authentication in an Angular Fullstack application?

Exploring the angular-fullstack (https://github.com/DaftMonk/generator-angular-fullstack) yeoman generator for the MEAN stack has been quite the learning curve for me as I navigate these technologies. One challenge I'm facing is understanding how to r ...

What measures can I take to ensure TypeScript transpiles prototype methods effectively?

Having some issues defining methods on a TypeScript class and then accessing them. Even though the methods are defined, it's giving an error that they don't exist. TypeScript: export class ColumnHeader extends JSONObject { // ... i ...

Navigate to a different web page within the body tag without changing the current URL by utilizing a hash symbol

I am working with two HTML files, index.html and about.html. My goal is to display the content of about.html within my index.html without navigating away from it. After observing many websites, I noticed that they often use #about in their URLs to dynamic ...

What is the best way to convert JSON data to HTML format?

I have a JSON file with the following data: [ { "key1": "value1", "key2": "value2" }, { "key3": "value3", "key4": "value4" }] The desired output format is: <h1>value1</h1><p>value2</p><h1>value3</h1><p>value4< ...

The console is throwing an error: ReferenceError: The variable $ has not been defined

I am having issues when trying to dynamically add a div upon selecting a checkbox in a Django template. The error message Uncaught ReferenceError: $ is not defined keeps appearing in the console. Here is the template code: {% extends 'base_layout.htm ...

What is the most effective way to transfer visitor hits information from an Express.js server to Next.js?

I've developed a basic next.js application with an express.js backend. What I'm aiming for is to have the server track hits every time a user visits the site and then send this hit count back to the next.js application. Check out my server.js cod ...

Ensure validity of input before navigating by using Angular's <a> ng-click function

I have a user input field and a "Go" button. When the user clicks on the button, I want to validate the input before redirecting to another page. However, the page keeps redirecting regardless of the validation. Instead of using the ng-click, I think it w ...

What is the process for declaring an exported type variable in React?

I have created a unique configuration in a different file: //config.js export const config = [ { id:0, name:"Config 1", }, { id:1, name:"Config 2", }, { id:2, name ...

Is there a simple way to display all the data from a JSON object even if the contents are unknown beforehand?

Greetings! I am Pearson's dictionary api. Here is a glimpse of what I receive from an api call: { "status": 200, "offset": 0, "limit": 10, "count": 10, "total": 135, "url": "/v2/dictionaries/entries?headword=dog", "results": [ { ...

Utilizing ngIf within HTML comments - a simple guide

My objective is to accomplish the following: <!-- directive: ng-my-if condition --> <link rel="stylesheet" ng-href="myStyle1.css"> <link rel="stylesheet" ng-href="myStyle2.css"> <link rel="stylesheet" ng-href="myStyle3.css"> < ...