AngularJS

时间:2016-07-09 22:19:02

标签: javascript angularjs json

我是Angular的新手,所以我认为我犯了一些愚蠢的错误,但仍然没有抓住它。 我已经创建了一个服务来获取一些数据,然后我已经在我的控制器中注入了该服务。

服务 -

  .service('getAllCompanies', ['$http', function ($http) {
    // AngularJS will instantiate a singleton by calling "new" on this function
    var url = "http://localhost:8000/companies/?page=";
    this.getCompanies = function(p) {
        return $http.get(url+p);
    };
  }]);

控制器 -

.controller('CompaniesallCtrl', ['getAllCompanies', function (companiesService) {
    var pageNumber = 1;
    this.companiesNumber = "";
    companiesService.getCompanies(pageNumber)
        .then(function(response){
            console.log(response.data.count);
            this.companiesNumber = response.data.count;
        }, function(error) {
            console.log(error);
        })
  }]);

我在控制台中收到此错误 -

TypeError: Cannot set property 'companiesNumber' of undefined
    at companiesall.js:17
    at processQueue (angular.js:16170)
    at angular.js:16186
    at Scope.$eval (angular.js:17444)
    at Scope.$digest (angular.js:17257)
    at Scope.$apply (angular.js:17552)
    at done (angular.js:11697)
    at completeRequest (angular.js:11903)
    at XMLHttpRequest.requestLoaded (angular.js:11836)

console.log(response.data.count)给出了正确的结果,所以我很困惑为什么它显示未定义。请帮忙!

2 个答案:

答案 0 :(得分:2)

我猜你在使用strict mode?然后then回调内的上下文将成为全局对象,但this确实是undefined。使用arrow function将保留词法范围(在这种情况下为控制器实例):

companiesService.getCompanies(pageNumber)
    .then(response => {
        console.log(response.data.count);
        this.companiesNumber = response.data.count;
    }, function(error) {
        console.log(error);
    })

bind来纠正背景:

companiesService.getCompanies(pageNumber)
    .then(function(response) {
        console.log(response.data.count);
        this.companiesNumber = response.data.count;
    }.bind(this), function(error) {
        console.log(error);
    })

答案 1 :(得分:2)

您还可以将控制器设置为函数范围内的变量。

类似的东西:

.controller('CompaniesallCtrl', ['getAllCompanies', function (companiesService) {
    var pageNumber = 1;
    var ctrl = this;
    ctrl.companiesNumber = "";
    companiesService.getCompanies(pageNumber)
        .then(function(response){
            console.log(response.data.count);
            ctrl.companiesNumber = response.data.count;
        }, function(error) {
           console.log(error);
        }) 
}]);
相关问题