簡體   English   中英

像承諾一樣鏈接RXJS5

[英]RXJS5 chaining like Promises

大家好,像諾言一樣,鏈接RXJS5結果的最佳方法是什么?

interface MyObj{
  name : string
  url: string
  html: any // async
}

// promise chaining, pretty simple
getMyObjWithPromise()
  .then(myObj=>{

   // promise, we get back html from myObj.url async
   return getMyObjHtmlWithPromise(myObj)
  })
  .then(myObj=>{

   // done, here we have myObj with html
  })

與RXJS5類似嗎? 我們需要跨流共享myObj,並異步修改obj props ...

使用Promises和鏈接then()調用,您可以修改傳遞給連續處理程序的結果。

如果要返回另一個Observable,RxJS中最相似的選項是map()運算符或concatMap() 在某些情況下, do也很有用,但無法修改傳遞的值。

Rx.Observable.fromPromise(getMyObjWithPromise())
  .map(myObj => {
    return myObj;
  })
  .concatMap(myObj => {
    // promise, we get back html from myObj.url async
    return Rx.Observable.fromPromise(getMyObjHtmlWithPromise(myObj));
  })
  .subscribe(myObj => {
    // done, here we have myObj with html
  });

請注意,通常至少需要一個訂閱者才能使Observable發出值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM