http请求后调用

时间:2015-10-26 20:21:54

标签: javascript angularjs httprequest

我想在收到数据并存储之后使用一个函数,但是我怎么没有得到我想要的结果我使用的代码。

有人可以向我提供有关我做错的一些细节吗?

我的代码:

    $http({
      method: 'GET',
      url: 'JsonLocation'
    }).then(
        function successCallback(response) {
            // this callback will be called asynchronously
            // when the response is available.
            self.responseData = response.data;
        }, 
        function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            console.log(response);
        }
    ).then(
        function completeCallback() {
            // called when the http request is finished.
            restyleData();
        }
    );

当页面加载并且所有内容都已设置好后,我可以通过开发人员选项运行restyleDate(),然后就可以了。但是我只想在加载所有内容后将其解雇而不是手动执行。

2 个答案:

答案 0 :(得分:1)

我建议改为:

$http({
  method: 'GET',
  url: 'JsonLocation'
}).then(
    function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available.
        self.responseData = response.data;
        // restyle is called after you save the result
        restyleData();
    }, 
    function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        console.log(response);
    }
);

答案 1 :(得分:0)

使用后使用catchfinally。如果您执行$scope.responseData = data,则可以在您的HTML中使用并自动填充数据。所以在html中,它看起来像{{responseData.description}}。如果您已将自己定义为此,那么它将是:{{self.responseData.description}}

或者,您可以将$ http调用包装在一个名为restyleData的函数中,然后调用该函数(就像您一样),它将显示数据。

$http({
  method: 'GET',
  url: 'JsonLocation'
}).then(
    function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available.
        self.responseData = response.data;
    })
     .catch( 
    function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        console.log(response);
    })
     .finally(
    function completeCallback() {
        // called when the http request is finished.
    });

restyleData();