Get a new ticket and then repeat the first request

Update:

I am extending the Http class when I deleteDocument()want to handle the error, then getTicket(), and then repeat the ma request deleteDocument()with a new one 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 receiving my new ticket, I want to repeat my first request with a new URL. Thanks

+1
source share
1 answer

I do not know if there is an easier way, but I would use concatMap()and recursively call deleteDocument()using the identifier returned from the previous call:

This should mimic 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 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 the demo: http://plnkr.co/edit/rUbLgEwtw7lSBueKJ5HN?p=preview

:

I'm your response: 21

willFail. concatMap , . id .

intercept() , HTTP-, this.getTicket().do() :

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

do() , , .

, , , .

, : Observable API

0

Source: https://habr.com/ru/post/1666900/


All Articles