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

What is the best way to handle this unconventional JSON structure?

Looking for some insight on retrieving process information from a VPS with PM2. However, the JSON string returned by PM2 is malformed, making it impossible to run JSON.parse(). An example of the output provided by PM2: '{data: 0, informations: " ...

What is the best way to include double quotation marks to create a valid JSON string in Ruby?

Whenever I send a JSON string to the third-party app, it ends up removing all the double-quotes from it. As a result, the response I get back is in this format: '{key:value, key2:value2}' This makes it impossible for me to parse the data as JS ...

Expand the contents inside a div without affecting the actual div

Is there a way to zoom out the contents of a div similar to how a browser zooms out a page? I'm working on an application that loads a page into a div. However, I want to load the content without scroll bars. This would require zooming out the conten ...

The background color of the active tab is updated upon loading the page

I have attempted to modify this code to change the background color of li tag on click. It successfully changes the background color when hovering or clicking, but unfortunately reverts back to the default color upon page refresh. I am looking for a soluti ...

The HTML grid is causing an irritating excess space on the right side of my website

After brainstorming an idea, I decided to create this website for testing purposes. However, the grid layout seems to be causing an unwanted margin on the right side of the page that is not associated with any HTML tag, disrupting the zoom functionality. ...

Challenges encountered with Material-UI elements

Attempting to implement the http://www.material-ui.com/#/components/drawer (Docked Example) component from Material-UI in conjunction with ReactJS. An error is encountered with the "=" sign in this line: handleToggle = () => this.setState({open: !this ...

Rendering a js.erb partial from one js.erb file to another using Rails and Jquery

Currently, I am facing a situation where I have duplicate js.erb code in the ajax responses of different models. To avoid this redundancy, I am looking to refactor the duplicate js.erb code by passing arguments into a js.erb partial. Can anyone guide me o ...

ng-options with automatically selected dynamic choices

<div class=" header-search pull-right"> <section style="margin-top: 15px" class="col col-6"> <label class="select"> <select style="width: 300px" ng-change="seletedCompanyChanged()" ...

Determine if a radio button is selected using Jquery

I am currently working on a script that should uncheck a radio button if it is checked, and vice versa. However, I'm facing an issue where the script always registers the radio button as checked even when it's not. Below is the code snippet in q ...

Guide on including a callback function in the renderCell columns of Material UI X Datagrid

When a button is clicked and the redux action is successful, I am trying to use a simple toast hook to display a message in the parent component where my Data grid is located. Can a callback be passed to utilize this hook from within the data grid? Here i ...

Google Feed API - Retrieving saved data from RSS feed cache

We have implemented the Google Feed API to display our latest blog posts on our website. However, even after 24 hours, our most recent post is still not appearing on our site. Despite confirming that the RSS feed contains the newest content, it seems that ...

Exploring the capabilities of Set() and the for..in loop in JavaScript

function removeDuplicates(menuArray) { let flatmenus = menuArray.flat();//This method combines child and parent arrays into one unique array let combinedMenu = new Set();//Creates an object that removes duplicate elements flatmenus.forEach(dish => ...

ExpressJS: How to resolve the undefined error in Express session

After using express-generator to create my project, I installed the express-session package. Below is how express-session is ordered in my app: app.js var expressSession = require('express-session'); app.use(logger('dev')); app.use( ...

How can I change a local datetime to UTCDatetime in Python prior to serialization?

I am looking to serialize the datetime object using json, but before serialization, I need to convert the local time to utc time. How can I achieve this conversion if I have the tzinfo available? import datetime def some_conversion(d): ??? # Assume th ...

Is there a way to incorporate CSS or tables when converting HTML to PDF using JavaScript?

While working on a project, I successfully converted an HTML file into a PDF. However, the output did not display the CSS design. Can anyone provide suggestions on how to include CSS design in the PDF file? Below is the JavaScript function code: $(funct ...

Displaying a preloaded image on the canvas

Once again, I find myself in unfamiliar territory but faced with the task of preloading images and then displaying them on the page once all elements (including xml files etc.) are loaded. The images and references are stored in an array for later retrie ...

The output from the Moment.js HTTP server is currently experiencing errors and is not displaying the expected

My first time working with JavaScript and the Momentjs library has not been smooth sailing. I am facing an issue where the output is not displaying as required. The goal is to show dates in the format "Day, date month year" (e.g., Tuesday, 14th May 2018). ...

Is the purpose of express.json() to identify the Request Object as a JSON Object?

app.js const express = require('express'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const helloRouter = require('./routes/hello'); const app = express(); app.set(& ...

Using React.PureComponent, the list component efficiently renders each item with optimized performance

We've developed a reusable list component in ReactJS. To address performance concerns, we decided to incorporate the shouldComponentUpdate method to dictate when our list component should re-render. public shouldComponentUpdate(nextProps: TreeItemInt ...

leafletjs: render Points of Interest (POIs) using canvas technology

I am looking for a way to efficiently draw multiple geo points using Leaflet and HTML5 canvas. My data source is geoJSON, but according to the documentation of Leaflet, drawing geo positions as canvas is currently not supported. var anotherGeojsonLayer = ...