2016-10-27 23 views
1

我繼續讀rxjs文檔,但在所有的運營商迷路..角2/RXJS - 需要一些幫助配料要求

這是我走到這一步,

let obs = Observable.from([1, 3, 5]) 

所以我需要這個要做的是take()一些來自陣列的量。在發佈請求中使用結果,當成功發佈時,我需要重新啓動該過程。我想收集所有結果,並隨着流程的進展保持進度(對於進度條)

我不需要所有代碼。我真正需要知道的是如何使用rxjs來分割這個陣列..發送它的一部分,並重新啓動過程,直到沒有剩下發送。

最終解決

var _this = this 

    function productsRequest(arr) { 
    return _this.chainableRequest('post', `reports/${clientId}/${retailerId}/`, loadedProductsReport, { 
     'identifiers': arr, 
     'realTime': true 
     })  
    } 

    let arrayCount = Math.ceil(identifiers.length/10) 
    let obs = Observable.from(identifiers)    
    .bufferCount(10) 
    .concatMap(arr => { 
     arrayCount-- 
     return arrayCount > 0 ? productsRequest(arr) : Observable.empty() 
    }) 


    let subscriber = obs.subscribe(
    value => console.log(value) 
) 

在父母

chainableRequest(method: string, endpoint: string, action: Function, data = {}, callback?: Function){ 
let body = (<any>Object).assign({}, { 
    headers: this.headers 
}, data) 


return this._http[method.toLowerCase()](`${this.baseUri}/${endpoint}`, body, body) 
      .map((res: Response) => res.json()) 
    } 

回答

2

環連接的請求方法,它在很大程度上取決於你想要達到的目的。

如果您想基於先前的Observable遞歸調用Observable,並且您不知道要調用多少次,那麼使用expand()運算符。

比如這個演示基於從以前的調用(count屬性)響應遞歸創建5個請求:

import { Observable } from 'rxjs/Observable'; 

function mockPostRequest(count) { 
    return Observable.of(`{"count":${count},"data":"response"}`) 
     .map(val => JSON.parse(val)); 
} 

Observable.of({count: 0}) 
    .expand(response => { 
     console.log('Response:', response.count); 
     return response.count < 5 ? mockPostRequest(response.count + 1) : Observable.empty(); 
    }) 
    .subscribe(undefined, undefined, val => console.log('Completed')); 

打印到控制檯:

Response: 0 
Response: 1 
Response: 2 
Response: 3 
Response: 4 
Response: 5 
Completed 

見現場演示:http://plnkr.co/edit/lKNdR8oeOuB2mrnR3ahQ?p=preview

或者,如果您只是想依次調用一堆HTTP請求(concatMap()運算符)或c所有所有的人一下子滅他們到達時(mergeMap()運營商):

Observable.from([ 
    'https://httpbin.org/get?1', 
    'https://httpbin.org/get?2', 
    'https://httpbin.org/get?3', 
    ]) 
    .concatMap(url => Observable.of(url)) 
    .subscribe(response => console.log(response)); 

打印到控制檯:

https://httpbin.org/get?1 
https://httpbin.org/get?2 
https://httpbin.org/get?3 

見現場演示:http://plnkr.co/edit/JwZ3rtkiSNB1cwX5gCA5?p=preview

+0

什麼即時試圖完成的就是把x數組中的項目 - >將它傳遞給http請求。 等待http請求完成,然後再次從頭開始傳遞項目。我已經嘗試了所有的例子,但沒有看到如何使我的工作做什麼即時通訊試圖做.. – hamobi

+0

@hamobi當時可以用'concatMap()'來完成一個運行Observable。那麼你想從同一個數組重新啓動進程還是什麼? – martin

+0

是的,我想重新從相同的數組進程。我想從數組中發送十個項目,然後接下來的十個項目,等等..直到我到達數組的末尾。謝謝:) – hamobi