角度服务,尝试实现重试 $http.get.(打字稿)



我试图为我的角度网络应用程序实现一些离线支持,但我无法让我的简单重试功能工作。我有一个使用以下代码的服务

constructor($http: ng.IHttpService, private $q: ng.IQService, private $interval: ng.IIntervalService, private $timeout: ng.ITimeoutService) {           
        this.httpService = $http;
    }
getCategories(updatedFunction: Function) {
        var deferred = this.$q.defer();
            this.httpService.get('/api/listCategories')
                .success((response) => {
                deferred.resolve(response);
            }).error(() => {
                this.$timeout(() => this.getCategories(), 10000);
            });
        return deferred.promise;
    }

在控制器上,我有以下内容。

    service.getCategories().then(c => {
                //Stuff in here
            });

如果 im 在线,服务工作正常,我得到了预期的数据。但是,如果 im 在开始时离线,我开始收到"GET http://correct_looking_path/ERR_FAILED,如果我逐步执行 js 文件,我可以知道它运行 this.httpService.get 方法,但立即失败 .error()。然后我连接,但仍然收到相同的错误消息和模式。httpService.get 方法每 10 秒运行一次,但始终失败。

如果我刷新它就可以了。

问题是你的 .error() 回调没有连接到你的延迟对象。您可能希望设置一个可选的 TypeScript 参数来传入延迟对象,以便可以链接递归调用。

getCategories(updatedFunction: Function, deferror?: angular.IDeferred<{}>) {
    var deferred;
    if (deferor) {
        deferred = deferror;
    } else {
        deferred = this.$q.defer();
    }
    this.httpService.get('/api/listCategories')
        .success((response) => {
        deferred.resolve(response);
    }).error(() => {
        this.$timeout(() => this.getCategories(deffered), 10000);
    });
    return deferred.promise;
}

我的问题是我的 .appcache 文件中的 NETWORK: 部分下没有我的 api 请求(/api/listCategories)。因此,它尝试使用一些不存在的缓存资源,而不是尝试发出真正的http请求。

最新更新