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

时间:2016-02-16 16:17:20

标签: angularjs typescript promise

我正在使用angular 1.5 with typescript,我无法从$ http promise返回的回调中访问this属性。

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

我有以下ServerAPI服务:

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) => {
    };
}

1 个答案:

答案 0 :(得分:2)

问题是这一行:

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

在维护词法范围以查找handlerResponded方法时,范围未在输出中完全保留。

你可以通过两种方式解决这个问题:

  • 内联您的处理程序函数,而不是将其作为您类的函数
  • 您可以bind对handlerResponded to the instance
  • 的调用

绑定示例:

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