get new ticket then retry first request

2019-03-01 04:40发布

问题:

Update:

I extend Http class, when I deleteDocument() I want handle error then getTicket() then retry ma request deleteDocument() with new this.TICKET :

@Injectable()
export class HttpService extends Http {
    public SERVER_URL: string = 'http://10.0.0.183:8080/alfresco/s/'
    public TICKET: string = ''

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }


    post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.post(url,body, options));
    }

    intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch(initialError => {
            if (initialError.status === 401) {
                return this.getTicket()
                    .do(res => {
                        // HERE I WANT RETRY MY FIRST REQUEST
                        this.TICKET = res.json().data.ticket
                    })
            } else {
                return Observable.throw(initialError);
            }
        })
    }

    getTicket() {
        return this.post(this.SERVER_URL + 'api/login', JSON.stringify({username: 'admin', password: 'admin'}))
    }


    deleteDocument(idFile: number) {
        return this.post(this.SERVER_URL + 'dms/file/delfile?idfile=' + idFile + '&alf_ticket=' + this.TICKET, {}).map((data: Response) => data.json())
    }
}

After receive my new ticket, I want retry my first request with new url. Thanks

回答1:

I don't know if there's any easier way but I'd use concatMap() operator and recursively call deleteDocument() with the the id returned from the previous call:

This should simulate your situation:

import {Observable} from 'rxjs';

function deleteDocument(willFail: bool, id) {
  return Observable.of("I'm your response: " + id)
    // process response and eventualy throw error
    .concatMap(val => {
      if (willFail) {
        return Observable.throw({response: val, message: "It's broken"});
      } else {
        return Observable.of(val);
      }
    })
    // recover from the error
    .catch(initialError => {
      return deleteDocument(false, initialError.response.length);
    });
}

deleteDocument(true, 42).subscribe(result => console.log(result));

See live demo: http://plnkr.co/edit/rUbLgEwtw7lSBueKJ5HN?p=preview

This prints to console:

I'm your response: 21

I'm simulating the error with willFail argument. Operator concatMap server here to distinguish between an error and a correct response. I'm also passing along the original id and to some processing with just for demonstration purposes.

In your case, you'd append to intercept() also all parameters necessary to reconstruct the original HTTP request and instead of this.getTicket().do() use:

return this.getTicket().concatMap(response => {
    var newBody = {id: response.ticketId};
    return this.post(originalUrl, newBody, ...);
});

Operator do() is mostly useful to just debug what's going on in your operator chains, it doesn't modify the chain in any way.

I don't know what your code actually does but I hope this makes sense to you.

Maybe a similar question to yours: Observable Continue calling API and changing parameters based on condition