Angular 4中的Http Request重试机制?

时间:2017-06-20 11:37:03

标签: angular typescript rxjs

我正在尝试在Angular4中实现请求/响应拦截机制。我对可观察对象是新手。

我维护两个拦截器阵列,一个用于请求,另一个用于响应。拦截器只不过是接受请求/响应对象并转换它们的函数。

sendRequest(req:Response):Observable<Response>{
    req= this.processRequest(req);

    This.http.request(req)
           .map( (res:Response)=>{
                return this.processResponse(res)
            })
            .catch(this.handleError)
}

handleError(err:Response):Observable<Response>{
    return Observable.throw(err);
}

基本错误处理工作正常。有时对于401异常,我想获得新的Auth令牌,并使用更新的Auth令牌重试相同的请求。

我在想的是引入错误拦截器数组。其中一个错误拦截器函数将检查它是否为401并将向服务器发出新的刷新请求,从而使后续错误拦截器函数无效。我假设需要切换可观察流。观察者最终会得到最新请求的回应。如何处理?

2 个答案:

答案 0 :(得分:2)

试试这个:

name = input('Enter Employee Name: ') # This should be an integer that represents the age of an employee at GPC try: age = int(input('Enter Employee Age: ')) except: print('Please enter a whole number') exit() job = input('Enter Employee Job: ') # This should be an integer that represents the salary of the employee at GPC try: salary = int(input('Enter Employee Salary to the Nearest Dollar: ')) except: print('Please enter only numbers without foreign characters') exit() salary_bonus = int(input('Enter employee bonus percentage '))/100 annual_income = (salary * salary_bonus) + salary import datetime now = datetime.datetime.now() # Current Year u = datetime.datetime.strptime('2016-12-30','%Y-%m-%d') d = datetime.timedelta(weeks=2) t = u + d # Data Output print('Employee: ', name) print('Age: ', age) print('Job Title: ', job) print('Annual Salary: ', round(salary,2)) print('Biweekly Paycheck: ', round(salary / 26, 2)) print('Bonus for', now.year, ': ', round(salary * salary_bonus, 2)) print('Actual Annual Income: ', round(annual_income, 2)) print('Your pay schedule will be:') print(t) print(t+d)

答案 1 :(得分:0)

我和http.request在同一级别上执行此操作似乎更容易,因为否则您需要跟踪所有重新发出请求的信息,但在这种情况下可能没有问题... < / p>

我猜你的拦截器正在对请求对象本身进行操作并返回请求对象的副本?例如,像......

transformResponse(response) {
  for(let interceptor of interceptors) {
    response = interceptor(response);
  }
  return response;
}

拦截器有以下原型:

interface Interceptor<T> {
  (rsp: T): V;
}

你能否将拦截器原型更改为

interface Interceptor<T> {
  (rsp: T): T | Promise<T> | Observable<T>;
}

然后你可以做......

transformResponse(responseObs: Observable<any>) {
  for(let interceptor of interceptors) {
    responseObs = responseObs.flatMap(interceptor);
  }
  return responseObs;
}

这将允许拦截器在响应上返回异步转换(例如重新发出请求)。