2016-11-15 76 views
0

我正在構建一個簡單的新聞應用程序。離子應用程序承諾只適用於第一視圖

它有兩個意見。

一個是故事列表,另一個是類別列表。每個人都有一個http.jsonp請求。

問題是,只有第一個視圖加載的控制器會得到一個返回的承諾。例如,如果我首先加載故事列表視圖(在我的瀏覽器中加載頁面#home),那麼http.jsonp請求會很好,我會看到我的「從故事承諾回來」警報。然後,當我點擊tab按鈕切換到類別視圖時,我看到了我的http.jsonp請求和返回的數據,因此必須調用控制器和getCats(),但它不會返回諾言 - 我從不會看到「從getCats承諾回來」警報。如果我使用完全相同的代碼,但首先通過在瀏覽器中加載類別視圖開始,然後類別填充正常,但是當我切換到故事視圖時,它再次不返回承諾。所以,這似乎與切換到應用程序中的第二個視圖有關。

如何獲得第二個視圖以返回承諾?

app.controller('listCtrl', ['$q','$scope','$state', 'StoriesFact', 
    function($q, $scope, $state, StoriesFact){ 

     StoriesFact.getStories($scope).then(function(response){ 
      alert("back from stories promise"); 
      $scope.stories = response; 
     }); 


}]); 


app.controller('sectionCtrl', ['$scope', 'StoriesFact', 
    function($scope, StoriesFact){ 

     StoriesFact.getCats().then(function(response){ 
      alert("back from getCats promise"); 
      $scope.categories = response; 
     }); 


}]); 

這裏是我廠與實際HTTP調用:

angular.module('reader.StoriesFact', []) 

.factory('StoriesFact', function($http, $q, $state) { 

    return { 
     getCats: function() { 
      var q = $q.defer(); 

      jsonURL = 'http://www.bendbulletin.com/somejson?callback=JSON_CALLBACK&pub=BendBulletin'; 

      $http.jsonp(jsonURL) 
       .success(function(data) { 
        q.resolve(data.categories); 
       }); 
      return q.promise; 
     }, 
     getStories: function() { 
      var q = $q.defer(); 

      jsonURL2 = 'http://www.bendbulletin.com/somejson?callback=JSON_CALLBACK&cats=1829480:1829507:1829469'; 

      $http.jsonp(jsonURL2) 
       .success(function(data) { 
        q.resolve(data.stories); 
       }); 
      return q.promise; 
     } 

    } 

}); 
+0

在這種情況下,您可以使用$ ionicView.enter。 (無論是第一次加載還是緩存視圖,此事件都會觸發。) – Hosar

+0

所以,並不是真正的答案,而是我去了另一條路線。我停止使用jsonp,而只是使用簡單的$ http.get。這確實會回報這個承諾。做更多的閱讀我發現應用程序不必處理Cors問題?所以我可以使用get。真的嗎? –

+0

在Ajax調用中,您總是需要處理Cors。 XmlHttpRequest與HttpRequest不同。至少據我所知,在前一種情況下,Cors是必需的。 – Hosar

回答

1

我改變了工廠的功能之一 - getStories爲純http.get,現在它似乎工作。我擺脫了我自己的承諾代碼 - $ q庫,並且只使用了http請求爲getCats調用返回的承諾。然而,我不得不改變工廠來調用它。

return { 
     getCats: function() { 
      jsonURL = 'http://www.bendbulletin.com/somejson?callback=JSON_CALLBACK&pub=BendBulletin'; 

      return $http.jsonp(jsonURL).then(function(response){ 
       return response.data; 
      }); 

     }, 
     getStories: function() { 
      jsonURL = 'http://www.bendbulletin.com/somejson?callback=JSON_CALLBACK&pub=BendBulletin'; 

      return $http.get(jsonURL).then(function(response){ 
       appCats = response.data; 
       return response.data; 
      }); 

我在控制器中沒有任何改變,現在我的承諾都返回。我是否認爲只有一種承諾可以返回到單一視圖?

相關問題