首页 > 解决方案 > AngularJS 如何在类控制器中访问 axios 的结果?

问题描述

所以我有一个小型 AngularJS 1.5 应用程序,我想在其中使用 axios lib 和 ES6 类控制器将 JSON 文件中的一些数据放在视图中。

angular.module('app', []).controller('listController', listController)

控制器代码:

class CompanyListController  {
     constructor(){
        this.list = ""
    }
    getList(){
        axios.get("./company.list.json")
        .then((response) => {                   
            this.list = response.data;
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        })
    return  list;
    }  }

看法:

  <div ng-controller = "listController as list">
      <div ng-bind = 'list.getList'></div>
      <div>
        {{ list.getList }}
      </div>
  </div>

视图中的 n-bind 给了我这个:

getList(){
  return s.a.get("./company.list.json")
  .then(e=>{this.list=e.data,console.log(e)})
  .catch(e=>{console.log(e)}),this.list}

我猜这是 webpack 缩小的结果。并且 ng-bind 还
从 axios 执行 console.log,它完全记录了 axios 的结果。 {{ list.getList }}什么都不扔。 axios类控制器语法必须在这个应用程序中。因此,Angular 确实将列表的值(null)放在了视图中,但在 axios 更改它之前。您能解释一下执行该操作的正确方法吗?

标签: javascriptangularjswebpackaxios

解决方案


axios 对服务器的异步请求。

class CompanyListController  {
     constructor(){
        this.listJson = "";
        this.getList();
    }

    getList(){
        axios.get("./company.list.json")
        .then((response) => {                   
            this.listJson = response.data;
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        });
    }
}

html应该是这样的。

 <div ng-controller = "listController as ctr">
  <div ng-bind="ctr.listJson">
 </div>

推荐阅读