【问题标题】:call after http requesthttp请求后调用
【发布时间】:2015-10-26 20:21:53
【问题描述】:

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

谁能提供一些关于我做错了什么的细节?

我的代码:

    $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(),然后它就可以工作了。但我只想在加载完所有内容后触发它,而不是手动执行。

【问题讨论】:

  • 删除第二个.then 语句并将您的restyleData 方法放入您的successCallback
  • 那么它的具体问题是什么?该功能有什么作用? I don't get result wanted 不是很确定
  • @ChristopherMarshall 该函数似乎在所有数据都在页面上之前被调用。我认为我的问题在于角度的 ng-repeat 是在我“重新设计”之前处理的。在所有数据都在页面上之后,我需要拥有它。
  • @charlietfl 我尝试从 json 文件中获取图像列表(src、title、desc、ect、、、)到数组中。应该将其加载到页面上,然后设置样式以使所有边距都正确。
  • 听起来你需要在指令中这样做并让元素首先呈现

标签: javascript angularjs httprequest


【解决方案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);
    }
);

【讨论】:

    【解决方案2】:

    使用 then 后使用 catchfinally。如果您使用$scope.responseData = data,则可以在您的 HTML 中使用,数据将自动填充。因此,在 html 中,它看起来像 {{responseData.description}}。如果您将 self 定义为这样,那么它将是:{{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();
    

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 2016-03-29
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多