2017-08-08 28 views
1

我處於嘗試爲我的http服務創建客戶端的Angular 4項目的早期階段。這些服務可以返回兩種情況之一:在角度項目中使用rxjs進行Http輪詢和條件邏輯

  1. 從服務的實際需要的JSON響應與200 HTTP狀態,或
  2. 代表工作令牌,我可以查詢的狀態一個GUID長時間運行的作業和http狀態202.

當服務返回200狀態時,我想直接返回它的json內容,這樣很容易。

當結果狀態是202時,我想用該令牌輪詢一個單獨的URL並接收一個包含狀態信息的json對象。當該狀態信息指示完成時,我想然後向最終的URL發出請求,以返回輸出。

我不知道如何處理我在請求中需要的條件邏輯。我懷疑我可以使用repeatWhen來監視輪詢請求的結果,但我無法弄清楚如何使用它。

http.request('/some/longrunning/job') 
    .flatMap((resp: Response) => { 
     if (resp.status !== 202) 
      return Observable.of(resp); 

     var job_token = resp.json().token; 
     return http.get('/jobstatus/' + job_token) 
      // result from this endpoint is a json object that looks something 
      // like { status: 'running' } or { status: 'complete' } 
      .repeatWhen(function (polling_resp: Observable<Response>) { 
       // How do I use polling_resp here to look at my http response? 
       // Do I need to explicitly subscribe to it? And if so, 
       // how then do I inspect the response and return the 
       // appropriate value to indicate whether or not to 
       // resubscribe via the repeatWhen? 
      }); 
    }); 

能有人給我如何在repeatWhen使用邏輯一些提示?我還沒有看到任何使用observable本身的內容來決定是否重新訂閱的例子。

回答

3

我認爲你正在尋找的東西更多的是這樣的:

http.request('/some/longrunning/job') 
    .flatMap((resp: Response) => { 
     if (resp.status !== 202) 
      return Observable.of(resp); 
     const token = resp.json().token; 

     return http.get(`/jobstatus/${token}`) 

     // You can use repeatWhen if you need more nuanced logic for 
     // how many times you want this to repeat, and how it should 
     // space out repeat attempts. 
     // This is just an example that guarantees at least 1 second between 
     // poll attempts so as to not overload the server 
     .repeatWhen(c => c.debounceTime(1000)) 

     // Ignore values until you have completed 
     .skipWhile(resp => resp.json().status !== 'completed') 

     // At this point you can stop the polling 
     .take(1) 

     // You don't actually care about the value of the response 
     // just that it has "completed" this maps that response to the 
     // call to fetch the result status. 
     .flatMapTo(http.get(`/jobresult/${token}`)) 

    }); 

本質上你的第一個條件是正確的,你需要揭開序幕的要求,並不斷重複它的第二部分,skipWhile部分將檢查結果並且不會傳播它們,直到狀態標記爲完成爲止,然後您可以使用flatMapTo直接將結果消息轉換爲另一個API請求,以獲得隨後得到傳播的結果實際

+0

非常好,謝謝!這很好地工作。 –