簡體   English   中英

調用AJAX API后如何更新Angular控制器?

[英]How can I update an Angular controller after an AJAX API call?

我正在創建一個天氣預報應用程序,使用ng-repeat迭代我的Forecast.dayArray以在頁面中創建不同的日期。

問題在於,用於填充每個“天”中數據的控制器沒有使用從ajax API調用中解析的信息進行更新。 相反,它僅保留初始化時使用的任何值。

//Initialize
var app = angular.module("weather", []);

app.controller("ForecastController", function(){
    this.array = ['a','b','c'];
});

ajaxCall(){
success: function(){
     app.controller.array.push('d'); //Doesn't seem to work
};

您可以在此處完整地查看代碼: 我的Codepen

您將必須使用$http服務。 您可以在控制器級別注入它,也可以通過工廠/服務對其進行抽象。

var app = angular.module("weather", []);

app.controller("ForecastController", ['$http', function($http) {
  this.array = ['a', 'b', 'c'];

  $http.get('someURLhere').then(function(response) {
    //http call success!
    this.array.push('d');
  }, function(error) {
    //error here! handle the error
    alert(error.data)
  })
}]);

您可以在此處閱讀如何使用$http服務。

在您的示例中, app.controller是用於設置新控制器的函數,因此在此行中:

app.controller.array.push('d');

app.controller不是對"ForecastController"的引用。

解決此問題的一種簡單方法是在$http服務的幫助下,從控制器內部進行AJAX調用:

app.controller("ForecastController", ["http", function ($http) {
    this.array = ['a', 'b', 'c'];

    $http
        .get(...)
        .then(function (response) {
            this.array.push('d');
        });
}]);

盡管這將起作用,但通常最好的做法是將獲取的數據分離到其自己的服務中,然后將該新服務注入到控制器中。

不必使用$ http服務,您仍然可以使用$ scope。$ apply從角度更新范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM