Understanding the concept of Angular factories in Javascript

app.service('WeatherService', function($http) {
   var service = {};

   service.getLocation = function() {
      return $http.jsonp("http://ipinfo.io/json?callback=JSON_CALLBACK");
   };

   service.getCurrentWeather = function(city) {
      var api = "http://api.openweathermap.org/data/2.5/weather?q=";
      var units = "&units=metric";
      var appid = "&APPID=061f24cf3cde2f60644a8240302983f2"
      var callback = "&callback=JSON_CALLBACK";

      return $http.jsonp(api + city + units + appid + callback);
   };
   return service;
});

Could someone provide an explanation of the functionality within this block of code? I'm unclear on the purpose of each variable. What does the getLocation function do? Does it define a function? Are all these variables combined to form a URL at the end, with the JSON retrieving data from the webpage being accessed?

Answer №1

This code snippet demonstrates how to define a reusable service within your application.

Here's an example of how to use it:

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

app.factory('WeatherApi', function($http) {
  var obj = {};

  obj.getLoc = function() {
    return $http.jsonp("http://ipinfo.io/json?callback=JSON_CALLBACK");
  };

  obj.getCurrent = function(city) {
    var api = "http://api.openweathermap.org/data/2.5/weather?q=";
    var units = "&units=metric";
    var appid = "&APPID=061f24cf3cde2f60644a8240302983f2"
    var cb = "&callback=JSON_CALLBACK";

    return $http.jsonp(api + city + units + appid + cb);
  };
  return obj
});

app.controller('someCtrl', function(WeatherApi) {
  var vm = this;
  WeatherApi.getLoc().then(function(response) {
    vm.location = response.data;
    console.log('Your location:' + JSON.stringify(vm.location));
  })
  WeatherApi.getCurrent('nyc').then(function(response) {
    vm.nycWeather = response.data;
    console.log('Weather in NYC:' + JSON.stringify(vm.nycWeather));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="someCtrl as vm">
</div>

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

Troubleshooting issue: AngularJS NVD3 line chart directive does not refresh after data update (not updating in real time)

I am currently facing an issue with the nvd3-line-chart directive in my AngularJS application. The chart does not redraw when I change the underlying model... As a newcomer to AngularJS, there may be something obvious that experienced programmers will not ...

Configuring select options using API data

I am currently retrieving my options from an API and have created a Const InputResponse to store the data: const inputResponse = [ { key: 'news', value: "news", datagrid:{ w:2, h:9, x:0, y:0, m ...

Having trouble retrieving prices using an npm package

There is a more effective way to retrieve prices using the npm package, node-binance-api, rather than relying on the "coin" variable that I am currently struggling with. If anyone could assist me in finding a better solution or the optimal method for fetch ...

When using selenium-python, every attempt to click a button consistently results in an error message

I've been trying to use Python-Selenium binding to click a button, but I haven't had any luck with various selectors so far. I'm currently using Chromedriver. Although I can select an element using elem = driver.find_element(by='xpath& ...

Styling material-ui textfield: Tips and tricks

I've been grappling with figuring out how to customize a material-ui TextField component. <TextField id="email" label="Email" className={classes.textField} value={this.state.form_email} onChange={this.handle_change('form_e ...

Is it possible for XSS attacks to exploit the HREF attribute when used with jQuery?

Burp suite displaying an error message. The application seems to have a potential vulnerability related to DOM-based cross-site scripting. Data is retrieved from the location and passed to jQuery() using the following statement: jQuery(location). ...

Calculate the total duration between two times and, if the difference is more than 10 minutes,

I need to calculate the duration between two dates, start_time and end_time. If the minutes component is greater than 10, I want to round up the hours component. For example: 12 minutes different - rounded up to 1 hour 1 hour 31 minutes difference - roun ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

The most effective method for transitioning an application from AngularJS to React-Typescript Micro Frontend

We are in the process of migrating from a monolithic AngularJS App to a ReactJS Micro Frontend App. Our current AngularJS App consists of 64 HTML pages, each rendered based on the API response containing LayoutId. Below is a snippet of the code structure: ...

Determine if two arrays share the same keys

Looking to compare two arrays and update them with matching keys while adding 0 for non-matching keys. For example: let obj1 = [ {"type": "Riesenslalom","total": 2862}, {"type": "Slalom", "total" ...

Scraping the Web with Python: Harnessing the Power of Selenium and

Seeking assistance with a problem I've encountered. I'm attempting to extract numbers from a specific website (link provided in the code below). Since the website utilizes JavaScript, my approach involves using selenium to load the page first and ...

Update DataTable 1.9 while preserving existing rows

I'm currently using dataTables js version 1.9 Periodically, an ajax call is made to the server to retrieve information that should be displayed in a table every 60 seconds or so. Although I can easily clear and repopulate the table like this: $(id) ...

How to show dates in AngularJS using local formatting

One situation I'm dealing with involves setting a date for an event. The challenge is that the date picker needs to display the date in a localized format based on the country or region. I've been exploring various solutions in AngularJS, but so ...

What are some solutions for troubleshooting a rapid-moving Selenium web driver?

My code is not functioning correctly and I need a better solution. The fast speed of execution makes it difficult for me to detect where the issue lies. Below is my current code: public static void main(String[] args) { //**************************** ...

Changes made to the data are not reflected in the user interface, but they are visible in the console

When working on a React project with input fields, I encountered an issue where the date data can be changed but doesn't get reflected in the UI. Instead, the updated data is visible in the console. The code snippet below showcases how I'm using ...

What is the proper way to initialize static variables in a JavaScript static class?

Within my javascript code, there exists a static class... var Logger = { logtofirefox: function (str, priority) { console.log(str); }, logtoie: function (str, priority) { alert(str); } } When invokin ...

Add a JQuery function to the button element in the HTML code

Currently, I am experimenting with AJAX to load a series of consecutive pages within a main page. The process is illustrated in the image below: Thanks to the guidance from this community, I have learned how to call content from other pages by utilizing t ...

Tips for showing error messages in response to exceptions

My function is supposed to display the response text that comes back from ex.responseText. However, every time I attempt it, it returns as "undefined" even though the text is there. onError: function (ex) { $('<div>' + ex._message + &a ...

Definition of union types in JavaScript using Typescript

Looking for assistance in creating a d.ts file for the union-type library found at https://github.com/paldepind/union-type Consider the following union type: let Maybe = Type({ Nothing: [] , Just: [Number] }) I am interested in setting up compi ...

Tips on choosing and showcasing information from jQuery date and time picker

I am struggling to show the selected data from a jQuery date and time picker and save it to a database using PHP with MySQL. I am not sure how to retrieve the information. Here is the jQuery code for the date and time picker along with a suggested jQuery f ...