2016-10-30 65 views
0

我正在構建一個MVC項目。我得到用戶的當前位置的城市,並將其放在網頁的右上角,這是第一個運行的JavaScript代碼。第二個JavaScript代碼運行得到該城市的天氣狀況。但是,當運行js獲取天氣的時候,城市名稱不是由第一個js設置的。如何運行2個JavaScript代碼以獲得正確結果

因此,我需要確保在運行第二個js之前,第一個js完成。我怎樣才能做到這一點?

這裏是我的js代碼。

上首先是jQuery代碼

<script> 
    function GetUsersInfo() 
    { 
     $.get("http://ipinfo.io", function (response) { 
      $("#cityName").html(''+response.city); 
      if ($("#cityName").html === "") 
      { 
       $("#cityName").html("İstanbul"); 
      } 
     }, "jsonp"); 
    } 
    GetUsersInfo(); 
</script> 

二碼爲角JS

<script> 
var app = angular.module("ZenHaberApp", []); 
app.controller("WeatherController", function ($scope, $http) { 
    var $city = document.getElementById("cityName").innerHTML 
    alert($city) 
    $http.get('http://localhost:62747/api/getweatherbycityname/' + $city). 
     success(function (data, status, headers, config) { 
      $scope.weathers = data.condition_temp; 
     }). 
     error(function (data, status, headers, config) { 
      alert(status); 
     }); 
}); 
</script> 

回答

1

在你情我願做相同流上的兩個請求,並使用async來管理它們。

帶有Async您可以使用waterfall方法來做到這一點:如果您正在使用角2

var async = require('async'); 

var app = angular.module("ZenHaberApp", []); 
app.controller("WeatherController", function ($scope, $http) { 

    async.waterfall([ 
     function (callback) { 
     // Make the request to get the city, if jsonp needed check $http.jsop method (remember to use the $sce module to trust the source) 
     // Assign the city to a $scope variable, which with angular simple add {{city}} to show to the user 
     // Async takes callbacks with two params (error, result) so you could do callback(err, city) 
     }, 
     function (city, callback) { 
     $http.get('http://localhost:62747/api/getweatherbycityname/' + city). 
     success(function (data, status, headers, config) { 
      callback(null, data) 
     }). 
     error(function (data, status, headers, config) { 
         callback(true); 
     }); 
     } 
    ], function (err, result) { 
     if (err) { 
     // Handle error 
     } else { 
     $scope.weathers = data.condition_temp; 
     } 
    });  
}); 
+0

談談回撥地獄大聲笑 – Derek

+0

@Derek其實異步被設計爲結束回調地獄 –

+0

承諾是旨在結束回調地獄。你發佈的代碼示例仍然有回調,因此仍然是回調地獄。承諾沒有回調。 – Derek

0

,也有一些是調用生命週期掛鉤

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

(我不知道如果是一個角度的第一個版本功能)

在那裏你可以定義沿着視圖的生命週期的腳本o r組件,然後您可以在不同的生命週期掛鉤中設置該腳本。

我希望有幫助。

1

幾個選項:

  1. 使用事件,加載數據後,你可以派遣一個全球性的事件並傾聽其他地方。 observer模式在jQuery中實現,因爲您已經使用jQuery,這很容易。 ($ .on和$ .trigger)

  2. 由於您使用的是jsonp,因此您可以使用jsonp回調。 在維基進一步解釋:https://en.wikipedia.org/wiki/JSONP#Callback_name_manipulation_and_reflected_file_download_attack

  3. 顯然是在利用間隔(setInterval的檢查元素的值),雖然這不是一個好辦法

在我看來選項1是最好的辦法。

我已經考慮到代碼是完全分開的,而且你不想將角度與第一部分耦合。

相關問題