在 HTTP 错误回调中访问“this”

access 'this' within http error callback

本文关键字:this 访问 HTTP 错误 回调      更新时间:2023-09-26

我有以下控制器和http请求。

我将连接错误设置为 false,并希望在 http 请求中的回调错误上将其设置为 true。

使用this时出现以下错误

Cannot set property 'connectionError' of undefined

当我使用$scope时,一切正常。

我已经阅读了以下文章 https://toddmotto.com/digging-into-angulars-controller-as-syntax/其中解释了很多关于thisscope的信息,并且有点理解在下面的代码中,最初将"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的温和解释。