Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 类范围在ajax成功回调中丢失_Angularjs_Typescript - Fatal编程技术网

Angularjs 类范围在ajax成功回调中丢失

Angularjs 类范围在ajax成功回调中丢失,angularjs,typescript,Angularjs,Typescript,我有一个简单的控制器和服务类,使用TypeScript进行编码。但是,从ajax($http服务)的成功回调中,该关键字的值未定义。因此,代码在(控制器类的)行代码处引发异常: this.$location.path('/index')//错误:此值未定义 请帮我解决这个问题 控制器的代码:(异常发生在方法“login():void”中) // /// 模块angularWithTs{ “严格使用”; 导出类LoginCtrl{ 静态$inject=[“LoginSrvc”、“SessionS

我有一个简单的控制器和服务类,使用TypeScript进行编码。但是,从ajax($http服务)的成功回调中,该关键字的值未定义。因此,代码在(控制器类的)行代码处引发异常:

this.$location.path('/index')//错误:此值未定义

请帮我解决这个问题

控制器的代码:(异常发生在方法“login():void”中)

//
/// 
模块angularWithTs{
“严格使用”;
导出类LoginCtrl{
静态$inject=[“LoginSrvc”、“SessionSrvc”、“$location”];
用户名:字符串;
密码:字符串;
错误消息:字符串;
_loginSrvc:loginSrvc;
_sessionSrvc:sessionSrvc;
_$location:ng.ILocationService;
构造函数(loginSrvc:loginSrvc,sessionSrvc:sessionSrvc,$location:ng.ILocationService){
this.username=“未定义”;
this.password=“未定义”;
this.errorMessage=“未定义”;
这是。_loginSrvc=loginSrvc;
这._sessionSrvc=sessionSrvc;
此.$location=$location;
}
login():void{
this.\u loginSrvc.getToken(this.username,this.password)
.然后(功能(响应){
SessionSrvc.setToken(response.access_token);//将令牌存储在cookie中
this.$location.path('/index');//错误:this的值未定义
},函数(错误响应){
//$scope.loginForm.errorMessage=errorResponse.error\u说明;
});
}
}
角度模块(“angularWithTs”).控制器(“LoginCtrl”,LoginCtrl);
}
服务代码:

    /// <reference path="sessionsrvc.ts" />
    /// <reference path="../models/authtoken.ts" />



module angularWithTs {
    "user strict";

    export class LoginSrvc {
        static $inject = ['$http', '$q', 'SessionSrvc'];
        _$http: ng.IHttpService;
        _$q: ng.IQService;
        _sessionSrvc: SessionSrvc;

        constructor($http: ng.IHttpService, $q: ng.IQService, sessionSrvc: SessionSrvc) {
            this._$http = $http;
            this._$q = $q;
            this._sessionSrvc = sessionSrvc;
        }


        getToken(username: string, password: string): ng.IPromise<AuthToken> {
            var result = this._$q.defer();

            var params = { grant_type: "password", userName: username, password: password };

            this._$http({
                method: 'POST',
                url: this._sessionSrvc.apiHost + 'token',
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj)
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    return str.join("&");
                },
                data: params,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;' }
                })
                .success(response => {
                    result.resolve(response);
                })
                .error(errorResponse => {
                    result.reject(errorResponse);
                });

            return result.promise;
        }    
    }

    angular.module("angularWithTs").service("LoginSrvc", LoginSrvc);
}
//
/// 
模块angularWithTs{
“用户严格”;
导出类LoginSrvc{
静态$inject=['$http','$q','SessionSrvc'];
_$http:ng.IHttpService;
_$q:ng.IQ服务;
_sessionSrvc:sessionSrvc;
构造函数($http:ng.IHttpService,$q:ng.IQService,sessionSrvc:sessionSrvc){
这是。$http=$http;
这个。$q=$q;
这._sessionSrvc=sessionSrvc;
}
getToken(用户名:string,密码:string):ng.IPromise{
var result=这个。$q.defer();
var params={grant_type:“password”,用户名:userName,密码:password};
这是.\uu$http({
方法:“POST”,
url:this._sessionSrvc.apiHost+“令牌”,
转换请求:功能(obj){
var-str=[];
用于(obj中的var p)
str.push(encodeURIComponent(p)+“=”+encodeURIComponent(obj[p]));
返回str.join(“&”);
},
数据:params,
标题:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8;'}
})
.success(响应=>{
结果:解决(反应);
})
.error(errorResponse=>{
结果:拒绝(错误响应);
});
回报结果。承诺;
}    
}
角度.module(“angularWithTs”).service(“LoginSrvc”,LoginSrvc);
}
在本部分中:

this._loginSrvc.getToken(this.username, this.password)
    .then(function (response) {
        SessionSrvc.setToken(response.access_token); // store token in cookies
        this._$location.path('/index'); // ERROR: the value of this is undefined
    }, function (errorResponse) {
        //$scope.loginForm.errorMessage = errorResponse.error_description;
    });
您正在传递两个函数作为承诺的resolve/reject,但这些函数不保存
this
的上下文

你可以通过:

或使用:

在本部分:

this._loginSrvc.getToken(this.username, this.password)
    .then(function (response) {
        SessionSrvc.setToken(response.access_token); // store token in cookies
        this._$location.path('/index'); // ERROR: the value of this is undefined
    }, function (errorResponse) {
        //$scope.loginForm.errorMessage = errorResponse.error_description;
    });
您正在传递两个函数作为承诺的resolve/reject,但这些函数不保存
this
的上下文

你可以通过:

或使用:


谢谢尼桑·托默。顺便说一下,我不知道“函数(响应)”和箭头函数(=>)之间的区别。它们似乎是匿名函数,不是吗?在javascript中,如果函数没有名称,即:
function(){…}
,则函数是匿名的。箭头函数总是匿名的。不同之处在于,使用箭头函数时,
的范围被保存,这与使用常规函数时不同。谢谢Nitzan Tomer。顺便说一下,我不知道“函数(响应)”和箭头函数(=>)之间的区别。它们似乎是匿名函数,不是吗?在javascript中,如果函数没有名称,即:
function(){…}
,则函数是匿名的。箭头函数总是匿名的。不同之处在于,使用箭头函数时,
的范围被保存,这与使用常规函数时不同。
this._loginSrvc.getToken(this.username, this.password)
    .then((response) => {
        SessionSrvc.setToken(response.access_token); // store token in cookies
        this._$location.path('/index'); // ERROR: the value of this is undefined
    }, (errorResponse) => {
        //$scope.loginForm.errorMessage = errorResponse.error_description;
    });
this._loginSrvc.getToken(this.username, this.password)
    .then(function (response) {
        SessionSrvc.setToken(response.access_token); // store token in cookies
        this._$location.path('/index'); // ERROR: the value of this is undefined
    }.bind(this), function (errorResponse) {
        //$scope.loginForm.errorMessage = errorResponse.error_description;
    });