AngularJs JSON endpoint modifier

I've been working on a simple weather app in Angular for practice, but I've hit a roadblock.

Here's the Angular JSON feed I'm using:

app.factory('forecast', ['$http', function($http) { 
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,NL&lang=NL_nl&units=metric') 
        .success(function(data) { 
          return data; 
        }) 
        .error(function(err) { 
          return err; 
        }); 
}]);

The feed loads into index.html successfully. Now, what I want is an input form on index.html that allows users to change the city from Amsterdam in the URL mentioned above, located in js/services/forecast.js. This way, people can view the weather of different cities.

To see the demo, click here:

I've tried numerous options over the past three days, but nothing seems to work. What is the correct approach here?

Answer №1

Start by setting up a "configurable" service :

app.factory('weatherService', ['$http', function($http) { 
    var city;
    var cities = {
        amsterdam: 'Amsterdam,NL',
        paris: 'Paris,FR'
    };
    var api_base_url = 'http://api.openweathermap.org/data/2.5/weather';
    var other_params = 'lang=NL_nl&units=metric';

    return {
        setCity: function(cityName){
            city = cityName ;
            console.log(city);
        },
        getWeather: function(cityName){
          console.log(city);
            if(cityName) this.setCity(cityName);
            if (!city) throw new Error('City is not defined');
            return $http.get(getURI());
        }
    }

    function getURI(){
        return api_base_url + '?' + cities[city] + '&' + other_params;
    }
}]);

Next, create a controller using the code below:

app.controller('forecastController', ['$scope', 'weatherService',function($scope,weatherService){

$scope.city = 'amsterdam' ;

    $scope.$watch('city',function(){
      console.log($scope.city);
      weatherService.setCity($scope.city);
    });

$scope.getWeather = function(){
  console.log('getting weather');
    weatherService.getWeather()
    .success(function(data){
    console.log('success',data);
    $scope.weatherData = data;
    }).error(function(err){
      console.log('error',err);
      $scope.weatherError = err; 
    });    
}; 
}]);

Create a template like the one shown below

<link rel="stylesheet" href="style.css" />

<div data-ng-controller="forecastController">

  <form>

    <label>
      <input type="radio" name="city" data-ng-model="city" data-ng-value="'amsterdam'">Amsterdam
    </label>
    <br/>
    <label>
      <input type="radio" name="city" data-ng-model="city" data-ng-value="'paris'">Paris
    </label>
    <br/>

    <button data-ng-click="getWeather()">Get Weather</button>

  </form>  

  <p class="weather-data">
    {{weatherData}}
  </p>
  <p class="weather-error">
    {{weatherError}}
  </p>

</div>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>

To see the functionality in action, click here : http://plnkr.co/edit/rN14M8GGX62J8JDUIOl8?p=preview

Answer №2

To incorporate a function in your factory, you can define your forecast as follows:

app.factory('forecast', ['$http', function($http) { 
 return {
     query: function(city) {
         return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&lang=NL_nl&units=metric') 
        .success(function(data) { 
          return data; 
        }) 
        .error(function(err) { 
          return err; 
        });
     }
 };

}]);

After defining the function in your factory, you can utilize it in your controller like this:

forecast.query('Amsterdam,NL').success(function(data) {
  $scope.weather = data;
});

Answer №3

Enhance the service code by creating a dedicated method that can be called multiple times with varying parameters (cities):

app.factory('forecast', ['$http', function($http) {
    return {
        load: function(location) {
            return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + location + '&lang=NL_nl&units=metric')
            .success(function(data) {
                return data;
            })
            .error(function(err) {
                return err;
            });
        }
    }
}]);

This modification allows for loading forecasts for different locations in the controller when needed:

forecast.load('Amsterdam,NL').then(function(data) {
    $scope.weather = data;
});

Check out the demo here: http://plnkr.co/edit/GCx35VxRoko314jJ3M7r?p=preview

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

Dynamically importing files in Vue.js is an efficient way to

Here's the code snippet that is functioning correctly for me var Index = require('./theme/dir1/index.vue'); However, I would like to utilize it in this way instead, var path = './theme/'+variable+'/index.vue'; var Inde ...

Angular 2: Encounter with 504 Error (Gateway Timeout)

I am struggling with handling errors in my Angular 2 application. Whenever the backend server is offline, an uncaught error appears in the console: GET http://localhost:4200/api/public/index.php/data 504 (Gateway Timeout) This is how my http.get me ...

Attempting to create an auto-suggestion tool that can process and accept multiple input values, filtering out only those that begin with a designated character

I've been working on implementing an auto-suggestion feature that displays suggestions with partial matches or values within the input box. The goal is for it to only provide suggestions that begin with a specific character, like the "@" symbol. Fo ...

What steps should be taken to modify an image following retrieval of data from the database?

When using the function getDataFromDb(), I am trying to retrieve the latest data from the database. Specifically, I want to use val["id"] as a condition to determine which image to display in the function GetImage. However, my attempts have not been succ ...

Modify variables in the child function to be utilized in the parent function

I need to create a scenario where a variable defined in a parent function is modified within a child function and then returned back to the parent as an updated variable. Here is the code I have attempted: let value = 20; console.log(value); // Output: ...

steps to create a personalized installation button for PWA

Looking to incorporate a customized install button for my progressive web app directly on the site. I've researched various articles and attempted their solutions, which involve using beforeinstallprompt. let deferredPrompt; window.addEventListener(& ...

Tips for preventing the appearance of two horizontal scroll bars on Firefox

Greetings, I am having an issue with double horizontal scroll bars appearing in Firefox but not in Internet Explorer. When the content exceeds a certain limit, these scroll bars show up. Can someone please advise me on how to resolve this problem? Is ther ...

Timeout of 30 seconds added to Axios network requests in Javascript

self.$axios .$get( `https://verifiedpro.herokuapp.com/getvmsstate?kiosk=${self.kiosk}` ) .catch(error => { console.log(error); location.reload(); }) .then(response => { console.log(respons ...

What could be causing the triggering of two AJAX requests in the given JavaScript code?

I have a code snippet that fetches data from the server. I want to trigger it on document.ready(). My expectation is that the first request is sent to the server, receives a response, and then the second request is made, and so forth. However, when I insp ...

default selection in AngularJS select box determined by database ID

Here is the scenario: ... <select ng-model="customer" ng-options="c.name for c in customers"> <option value="">-- choose customer --</option> </select> .... In my controller: $scope.customers = [ {"id":4,"name":"aaaa", ...

Guide to transforming JSON data from a webpage into an ArrayList on an Android platform

Is there a way to extract and store data from a JSON object fetched from a website into ArrayLists in an Android application? This particular JSON object represents users and is structured as follows: {"Users":[{"name":"Kane","lon":"4.371645","lat":"31.3 ...

There was an issue with the origin null not being permitted by Access-Control-Allow-Origin

Possible Duplicate: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin I am currently working on a weather application that runs smoothly in browsers. However, when I try to deploy it on my Android phone, it encounters iss ...

AngularJS is throwing an error because it can't find a function called 'undefined' in Controller xxx

Just diving into the world of Angular. I'm following an example from a reputable book, but encountering an issue with the Cart Controller not being recognized as a function. Here's the code snippet causing trouble: HTML: <!DOCTYPE html> & ...

How can I dynamically generate multiple Reactive Forms from an array of names using ngFor in Angular?

I am in the process of developing an ID lookup form using Angular. My goal is to generate multiple formGroups within the same HTML file based on an array of values I have, all while keeping my code DRY (Don't Repeat Yourself). Each formGroup will be l ...

Locating the matching value in the <select> element and showcasing it

I'm trying to create a function where selecting an option from one dropdown menu will display the corresponding value in another column. For instance, if someone chooses "3" from the first dropdown, the value displayed in the third column should be "3 ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

Trouble with $http response not appearing in AngularJS application

Currently, I am in the process of developing an angularjs application and encountering a challenging issue with setting up the $http connection to a php file. The header is displaying a response that I echoed from php. Nevertheless, two key problems persis ...

The attribute interface overload in Typescript is an important concept to

Consider a scenario where there are multiple payload options available: interface IOne { type: 'One', payload: { name: string, age: number } } interface ITwo { type: 'Two', payload: string } declare type TBoth = IOne ...

Create a list using ReactJS

I've been working on rendering a dynamic list in JSX, but I'm facing issues displaying the items. Below is my code snippet where I attempted to use useState const [orderList, setOrderList] = useState([]) and setOrderList(prev => [...prev, chil ...

Having trouble importing a React component from a different directory?

I have included the folder structure for reference. Is there a way to successfully import the image component into the card component? No matter which path I try, I keep encountering this error: ./src/Components/Card/Card.js Module not found: Can't ...