简体   繁体   English

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

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

I'm creating a weather forecast app, using ng-repeat to iterate on my forecast.dayArray to create the different days in the page. 我正在创建一个天气预报应用程序,使用ng-repeat迭代我的Forecast.dayArray以在页面中创建不同的日期。

The issue is that the controller used to fill in the data in each "day" isn't being updated with the information that is parsed from the ajax API call. 问题在于,用于填充每个“天”中数据的控制器没有使用从ajax API调用中解析的信息进行更新。 Instead, it just keeps whatever value it was initialized with. 相反,它仅保留初始化时使用的任何值。

//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
};

You can see the code in its entirety here: My Codepen 您可以在此处完整地查看代码: 我的Codepen

You will have to use $http service. 您将必须使用$http服务。 You can either inject this at your controller level, or abstract it with a factory/service. 您可以在控制器级别注入它,也可以通过工厂/服务对其进行抽象。

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)
  })
}]);

You can read on how to use the $http service here . 您可以在此处阅读如何使用$http服务。

In your example, app.controller is a function that is used to set up a new controller, so in this line: 在您的示例中, app.controller是用于设置新控制器的函数,因此在此行中:

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

app.controller is not a reference to your "ForecastController" . app.controller不是对"ForecastController"的引用。

A simple way to fix this would be to make the AJAX call from within the controller, facilitated by the $http service: 解决此问题的一种简单方法是在$http服务的帮助下,从控制器内部进行AJAX调用:

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

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

While this will work, it is typically considered better practice to separate the data fetching into its own service and inject that new service into your controller. 尽管这将起作用,但通常最好的做法是将获取的数据分离到其自己的服务中,然后将该新服务注入到控制器中。

不必使用$ http服务,您仍然可以使用$ scope。$ apply从角度更新范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM