Javascript &引用;无法设置未定义的属性";AngularJS中的错误
我是个新手,所以我认为我犯了一些愚蠢的错误,但仍然没有抓住它。 我创建了一个服务来获取一些数据,然后将该服务注入到我的控制器中 服务-Javascript &引用;无法设置未定义的属性";AngularJS中的错误,javascript,angularjs,json,Javascript,Angularjs,Json,我是个新手,所以我认为我犯了一些愚蠢的错误,但仍然没有抓住它。 我创建了一个服务来获取一些数据,然后将该服务注入到我的控制器中 服务- .service('getAllCompanies', ['$http', function ($http) { // AngularJS will instantiate a singleton by calling "new" on this function var url = "http://localhost:8000/compan
.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)
log(response.data.count)给出了正确的结果,所以我不明白为什么它显示为未定义。请帮忙 我猜你在用什么?然后回调中的上下文将是全局对象,但这个实际上是未定义的。用于保留词法作用域(本例中为控制器实例):
或更正上下文:
companiesService.getCompanies(pageNumber)
.then(function(response) {
console.log(response.data.count);
this.companiesNumber = response.data.count;
}.bind(this), function(error) {
console.log(error);
})
您还可以将控制器设置为函数范围内的变量
比如:
.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);
})
}]);
var self=这个;self.compainesNumber=“”;然后(函数(响应){self.companiesNumber=response.data.count;});
.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);
})
}]);