在 HTTP 错误回调中访问“this”
access 'this' within http error callback
我有以下控制器和http请求。
我将连接错误设置为 false,并希望在 http 请求中的回调错误上将其设置为 true。
使用this
时出现以下错误
Cannot set property 'connectionError' of undefined
当我使用$scope
时,一切正常。
我已经阅读了以下文章 https://toddmotto.com/digging-into-angulars-controller-as-syntax/其中解释了很多关于this
和scope
的信息,并且有点理解在下面的代码中,最初将"connectionError"设置为false的this
与回调Error函数中的this
不同this
指的是它所在的函数......?!?(好吧,这就是我目前正在解释的内容...
所以我的问题是 - 有没有办法将"连接错误"设置为 true。或者这是一个$scope
更适合的经典例子?
法典:
var userApp = angular.module('UserApp', []);
userApp.controller('UserListCtrl', ['$scope', '$http', function ($scope, $http){
var type = this;
type.users = [];
// doesn't work
this.connectionError = false;
// works
$scope.connectionError = false;
// get the data
$http.get('./types/users.json')
// on success
.then(function successCallback(response){
type.users = response.data;
},
// on error
function errorCallback(response){
// doesn't work
this.connectionError = true;
// works
$scope.connectionError = true;
});
}]);
您会收到错误,因为它在另一个函数中使用时具有不同的值。
要在错误回调中使用控制器函数this
,请将this
分配给控制器中的另一个变量。在这种情况下,您已经使用变量完成了type
所以使用它!
function errorCallback(response){
type.connectionError = true;
});
关于$scope
,特别是如果您使用的是控制器作为语法,请强烈避免使用它。
错误处理程序中this
的上下文不是来自主控制器函数的上下文。在严格模式下,函数调用的上下文undefined
。
要解决此问题并访问控制器的this
,请使用bind()
方法:
$http.get('./types/users.json')
// on success
.then(function successCallback(response){
type.users = response.data;
},
// on error
function errorCallback(response){
// Now will work
this.connectionError = true;
// works
$scope.connectionError = true;
}.bind(this));
有关更多详细信息,请参阅this
的温和解释。
相关文章:
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- 为什么我不能在 ajax 成功中访问 $(this)
- 在接受功能上访问燃料UX标语牌中的“this”
- $.each 中的“this”,当需要使用“this”访问对象的函数时
- 在jQuery中,我如何从$.ajax回调函数访问$(this)
- TypeScript:在对象文字字段中的访问器中访问外部“this”
- JavaScript 访问函数构造函数中的“this”
- React Native can'无法在render()方法之外访问this.ops
- 通过函数传递“this”时,我是否可以无法访问“this”的属性
- 如何使用“self = this”访问类属性
- 使用“this”访问对象的值
- arguments属性可以由this访问.some_function.arguments?实际上我无法解释
- 使用let初始化的函数在被this访问时不被替换
- 隐藏匿名JavaScript函数中的变量,但使用“this”访问它们
- 如何使用$(this)访问调用Javascript函数的按钮的id
- 在Javascript中无法通过this访问const变量
- 如何在jQuery中使用$(this)访问子元素?
- 无法使用“this”访问对象.“this”指向“窗口”对象
- 使用jQuery的$(this)访问内部文本
- 使用this访问对象内的对象名称