2016-08-23 70 views
-1

我有一個AngularJS功能的情況下在我的$ HTTP甚至在我的第一個函數執行完畢

這裏是我的代碼示例格式運行:

$scope.function = function(){ 
    $scope.functionOne(); // This function declares all the scope variable that I need to produce to throw on my API 
    $scope.functionTwo(); // This is the function that throws a request to my API via $http.post 
} 

我需要這些變量,但每一個變量只是一個空字符串,當它達到我的後端,因爲$ HTTP拋出的請求的第一個函數完成之前

UPDATE

$scope.functionOne = function(){ 
var geocoder = new google.maps.Geocoder(); 
if(geocoder){ 
    // console.log("dean") 
    // console.log($scope.dealership.address); 
    // console.log($scope.dealership.suburb) 
    geocoder.geocode({ 
     'address': $scope.dealership.address + ', ' + $scope.dealership.suburb || "1/53 Township Drive, West Burleigh" 
    }, function(result, status){ 
     // console.log("armada"); 
     // console.log(status); 
     if(status == google.maps.GeocoderStatus.OK){ 
      console.log(result); 

      var center_lat = result[0].geometry.location.lat(); 
      var center_lng = result[0].geometry.location.lng(); 

      var lat = result[0].geometry.location.lat(); 
      var lng = result[0].geometry.location.lng(); 

      $scope.$apply(); 
     } 

     $scope.map.center.latitude = center_lat; 
     $scope.map.center.longitude = center_lng; 

     $scope.map.markers.pop(); 
     $scope.map.markers.push({ 
      latitude: lat, 
      longitude: lng 
     }); 
     $scope.dealership.latitude = lat; 
     $scope.dealership.longitude = lng; 

     $scope.$apply(); 
    }); 
} 
}; 

$scope.functionTwo = function(){ 
    $scope.loadingData = true; 
    // The code below is a factory on a scope variable 
    $scope.dealership.create().then(function(response){ 

}); 
} 
+0

任何機會,你可以發佈一個例子,你實際上是使用$ HTTP調用? –

+0

這是一個小*太* *抽象。請提供更具體的樣本。 – deceze

+0

答案似乎沒有提及這是因爲$ http.post是一個異步函數。這意味着它以非阻塞的方式與其他代碼並行執行。 – byxor

回答

0

依賴函數調用的更好選項是使用回調函數。

嘗試在第一個函數的回調函數中調用第二個函數。

編輯:

的角的另一種方法是使用Promises

你可以參考更多關於它在https://docs.angularjs.org/api/ng/service/ $ Q enter link description here

+0

現代的方式通常是返回一個'承諾'。 – deceze

+0

@deceze是返回'Promise'也可以。感謝您的建議 –

+0

我對我的問題做了更新 –

0

承諾是要走的路。一旦你完成了functionOne解決變量,然後返回承諾。一旦成功解決承諾運行第二種方法。

希望這有助於

快樂學習

Vatsal

+0

我對我的問題做了更新 –

相關問題