无法从$http回调访问此内容



我正在使用带有打字稿的角度 1.5,我无法从从 promise 返回$http回调中访问this属性。

当我尝试从回调访问私有方法时,"this"未定义

我有以下服务器API服务:

export class ServerAPI implements IServerAPI {
    static $inject:Array<string> = ['$http', '$q'];
    constructor(private $http:ng.IHttpService,
                private $q:ng.IQService) {
    }
    postHandler(partialUrl:string, data?:any, config?:any):ng.IPromise<any> {
        let url = this.buildUrl(partialUrl);
        var result:ng.IPromise< any > = this.$http.post(url, data, config)
            .then((response:any):ng.IPromise<any> => this.handlerResponded(response, data))
            .catch((error:any):ng.IPromise<any> => this.handlerError(error, data));
        return result;
    }
    private handlerResponded(response:any, params:any):any {
        response.data.requestParams = params;
        return response.data;
    }
    private handlerError(error:any, params:any):any {
        error.requestParams = params;
        return error;
    }
}

由user.service使用:

export class UserService implements IUserService {
    static $inject:Array<string> = ['$q', 'serverAPI'];
    constructor(private $q:ng.IQService,
                private serverAPI:blocks.serverAPI.ServerAPI) {
        var vm = this;
        $rootScope.globals = $rootScope.globals || {};
        $rootScope.globals.currentUser = JSON.parse($window.localStorage.getItem('currentUser')) || null;
        this.getUserPermissions();
    }
    private getUserPermissions:() => IPromise<any> = () => {
        var promise = this.serverAPI.postHandler('MetaDataService/GetUserPermissions',
            {userID: this.getUser().profile.UserID})
            .then((res) => {
                this.updateUser('permissions', res.GetUserPermissionsResult); // NOT WORKING, this is undefined
            })
            .catch((response:any):ng.IPromise<any> => {
                this.updateUser('permissions', res.GetUserPermissionsResult); // NOT WORKING, this is undefined
            });
        return promise;
    };
    private updateUser:(property:string, value:any) => void = (property, value) => {
    };
}

问题是这一行:

.then((response:any):ng.IPromise<any> => this.handlerResponded(response, data))

虽然为了查找handlerResponded方法而保留了词法范围,但输出中并未完全保留范围。

您可以通过两种方式解决此问题:

  • 内联您的处理程序函数,而不是将其作为类上的函数
  • 您可以bind对处理程序的调用响应实例

绑定示例:

.then((response:any):ng.IPromise<any> => this.handlerResponded(response, data).bind(this))

最新更新