简体   繁体   中英

Calling RESTful apis through ajax and angular js

If the URL that is to be hit has to be passed variables ie API.openweathermap.org/data/2.5/forecast/city?name=[random_city_name]&APPID=[key_value] ,

then what is better to use ajax or angular js.

If I am using ajax then how am I supposed to pass the variable? I am a newbie in this. So, need your help.

Your url seems to have request parameters and assuming you are using angular1

For this, you can use

$http({
    method: 'GET',
    url: url,
    headers: {},
    params : {}
})

Put your parameters as a map and $http will take care of creating an url. Refer $http documentation here

what is better to use ajax or angular js

You can't compare as AJAX provides a way to communicate (send requests and get responses) with the server asynchronously and AngularJS used AJAX to extends the 2-way data binding.

To accomplish the above situation we can use Angular $http service.

var baseUrl = API.openweathermap.org/data/2.5/forecast/city;
var method = 'GET';
var data = {};
var params = {
   "name":cityName,
   "APPID":key_value
};

$http({
    method: method,
    url: baseUrl,
    params : params,
    data : data
}).then(function mySucces(response) {
    $scope.data = response.data;
}, function myError(response) {
    $scope.data = response.statusText;
});
You can use angular $http service and pass your params like below.

var UserInfo = function() {
    $scope.userID = "1111";
    var req ={
        "method":"GET",
        "url": someURL + $scope.userID,
        "withCredentials":true
    };
    $http(req).then(function(response) {
        alert('success');
    }, function(response) {
        alert('error');
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM