2016-10-10 1 views
1

アップデート最初の要求を再試行新しいチケットを取得:その後、新しいthis.TICKETとミリアンペア要求deleteDocument()を再試行getTicket()、私deleteDocument()が、私はエラーを処理したいとき、私は、HTTPのクラスを拡張

その後、

@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()) 
    } 
} 

は後に私の新しいを受け取りますチケット、私は新しいURLで私の最初のリクエストをやり直したい。どんな簡単な方法があるかどうおかげ

+0

あなたはどこ実際の要求にコードを追加していただけますか?あなたの再試行メソッドはクエリメソッドへの新しい呼び出しになるので、その署名を知る必要があります。 – Supamiu

+0

ご迷惑をおかけいたしますが、ここにいるのです(アップデートをご覧ください) – istiti

答えて

0

は私は知りませんが、私はconcatMap()演算子を使用して再帰的にidは前の呼び出しから返されてdeleteDocument()を呼びたい:

これはあなたの状況をシミュレートする必要があります。

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)); 

ライブデモを参照してください: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 Continue calling API and changing parameters based on condition