javascript - AngularJs : $http chaining

标签 javascript angularjs http

我有这两个函数,这是代码示例

var getRangeTime = function(numSerie){
      $http.get("data/tempsgammes.json").then(function(res){
          return $scope.time = res.data[numSerie].temps
    })}

var updateScreen = function() {
      $http.get("http://localhost:5000").then(function(response){
        $scope.numSerie = response.data.refDetail.Num_Serie
        $scope.numTeam = response.data.team
        $scope.t = getRangeTime($scope.numSerie)
        //Rest of code the code
    }

这是我想做的:

首先,我调用函数updateScreen()来获取序列号(numSerie),然后根据numSerie的值>,另一个函数getRangeTime()将被执行来获取时间,然后函数updateScreen()将使用getRangeTime()的结果继续执行

这里的问题是异步的,我的意思是 updateSreen() 应该等待 getRangeTime() 直到她返回所需的值,这是一种异步等待

我已经尝试过,但它不起作用,实际上我不太知道如何使用它们,我在这里搜索并尝试了现有的解决方案,但效果也不太好,我总是得到未定义

谁能帮我吗?

最佳答案

在这种情况下,您应该使用 promise 链来依次调用请求。

function updateScreen(){
    return $http.get("http://localhost:5000")
}

function getRangeTime(){
   return  $http.get("data/tempsgammes.json")
}

$scope.calltwoFunctions = function() {
     updateScreen()
       .then( function( response )
        {
            $scope.numSerie = response.data.refDetail.Num_Serie
            $scope.numTeam = response.data.team
            return getRangeTime();
        })
        .then(function(response){
           console.log(response.data);
        })
}

关于javascript - AngularJs : $http chaining,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45788622/

相关文章:

javascript - 将 Firebase 与 Webpack 和 TypeScript 结合使用

javascript - 当应用 CSS 省略号并且 offsetwidth 不断返回 0 时,用于使文本出现在工具提示中的 Angular 指令?

javascript - 疯狂使用 Angular Directive(指令)和范围更新

angularjs - 如何在 Angularjs 的单个模块中创建多个自定义过滤器

javascript - 什么是 X-REMOVED HTTP header ?

javascript - var varName = function funcName() {}

AngularJS 从另一个文件调用函数

apache - 405 方法不允许 : PUT http://localhost:3030/dataset/data? 默认

ruby-on-rails - Ruby - cURL 为 nil :NilClass error 抛出未定义的方法 `post'

javascript - 如何将更快的语言与 Express.js 后端集成?