$Http Which one should I use?

Asked

Viewed 344 times

3

The $http has two examples. I would like you to help me because I don’t know which is the most useful

There is the :

var chamada = function () {
    return $http.get('https:url/exemplo.json')
        .then(function (response) {
            return response.data;
         });
    }

and the :

 var outraChamada = function () {
     return $http.get('https:url/outroExemplo.json')
         .success(function (data) {
             return data;
         }).error(function (status) {
             return status;
         })
     }

What should I choose? Is there any way to return the date if it is changed in the Web Service (without calling the function)?

  • "Is there any way to give me back the date if it is changed in the Web Service (without having to call the function)?" Are you saying something magical, where he would update himself without calling the web service? If that’s it, no, there’s no magic to it yet(not ready).

  • 1

    success and error are callbacks marked as deprecated, use then. Source: https://docs.angularjs.org/api/ng/service/$http

2 answers

3


Use the then as @lbotinelly said success and error are deprecated.

$http.get('https:url/exemplo.json')
    .then(function(response) {
        return response.data;
    }, function(err) {
        console.log(err);
    });

Is there any way to give me back the date if it is changed in Web Service(without calling the function)?

A: No, there’s no way your page can know "alone" if something was changed in the back end. There are some alternatives, one of them is to create a function that does a check every x minutes and check if something has changed, in this case you can use the $timeout.

1

$http get.() returns an object Promise, that allows us to chain functions as if they were synchronous.

The chained function then() takes two arguments: a Handler successful and a Handler error.

The correct is to use this format available on documentation (the Success and error are deprecated):

$http.get('/someUrl', config).then(successCallback, errorCallback);

Example:

var chamada = function () {
    return $http.get('https:url/exemplo.json').then(this.sucesso, this.erro);
}

this.sucesso = function(response) {
    return response.data;
}

this.erro = function(error) {
    console.log('Não foi possível obter os dados: ' + error.data);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.