1

I follow an angular tutorial and because the link that I have to use in my service changed since the tutorial was made, I am confuse how to use the second param in params, which is the appid required now by the api.openweathermap.org.

function weatherFactory($http) {
    return {
        getWeather: function(city, country) {
            var query = city + ', ' + country;
            var key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            return $http.get('http://api.openweathermap.org/data/2.5/weather?', {
                params: {
                    q: query,
                    appid: key
                }
            }).then(function(response) {
                // //then() returns a promise which 
                // is resolved with return value of success callback
                return response.data.weather[0].description;
            });
        }
    };
}

The link should look like this:

http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1

So I put the key like the second params in get, but I don't know how to add this & in front of appid, to be like in the link example from them. Can someone please tell me how to do it?

1
  • what your question exactly? , how to create the url?, how to add params? Commented Mar 2, 2017 at 8:40

2 Answers 2

2

Try it like in this demo fiddle. The separator & is added automatically by AngularJS.

$http({
  method: 'GET',
  url: 'http://api.openweathermap.org/data/2.5/weather?',
  params: {
    appid: 'b1b15e88fa797225412429c1c50c122a1',
    q: 'London,uk'
  }
}).then(function(response) {
   return response.data.weather[0].description;
});

Result:

http://api.openweathermap.org/data/2.5/weather?&appid=b1b15e88fa797225412429c1c50c122a1&q=London,uk

Sign up to request clarification or add additional context in comments.

Comments

1

but I don't know how to add this & in front of appid, to be like in the link example from them

& is the separator character for query strings. It should be added when converting the object you pass to params to a query string.

You aren't converting the object to a query string. Angular is. So do nothing. Angular will do that for you.


If you were converting it manually, you would do something like:

var pairs = [];
Object.keys(obj.params).forEach(function (key) {
    pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
});
var query_string = pairs.join("&");

… but as mentioned above. That's done for you by the library.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.