2016-09-01 56 views
0

我對cyclejs和rxjs一般都很陌生,希望有人能幫我解決我的問題。 我想爲我的理解構建一個演示應用程序,並堅持在DOM上呈現JSON對象。在RxJS中處理JSON對象

  • 我的演示應用程序在過去7天內調用NASA附近的地球對象API並嘗試顯示它們。
  • 底部有一個Load More按鈕,點擊後會加載前7天的數據(Today - 7 upto Today - 14)。
  • 我從API得到的迴應是如下

    { "links" : { "next" : "https://api.nasa.gov/neo/rest/v1/feed?start_date=2016-09-06&end_date=2016-09-12&detailed=false&api_key=DEMO_KEY", "prev" : "https://api.nasa.gov/neo/rest/v1/feed?start_date=2016-08-25&end_date=2016-08-31&detailed=false&api_key=DEMO_KEY", "self" : "https://api.nasa.gov/neo/rest/v1/feed?start_date=2016-08-31&end_date=2016-09-06&detailed=false&api_key=DEMO_KEY" }, "element_count" : 39, "near_earth_objects" : { "2016-09-06" : [{ some data }, { some data }], 2016-08-31: [{...}], ... } }

我感興趣的near_earth_objects JSON對象,但我不能把它映射東陽它作爲一個對象。 我該如何處理這種情況?下面是代碼,我有

function main(sources) { 
    const api_key = "DEMO_KEY"; 
    const clickEvent$ = sources.DOM.select('.load-more').events('click'); 
    const request$ = clickEvent$.map(() => { 
     return { 
      url: "https://api.nasa.gov/neo/rest/v1/feed?start_date=2015-09-06&end_date=2016-09-13&api_key=" + api_key, 
      method: "GET" 
     } 
    }).startWith({ 
     url: "https://api.nasa.gov/neo/rest/v1/feed?start_date=2016-08-31&end_date=2016-09-06&api_key=" + api_key, 
     method: "GET" 
    }); 
    const response$$ = sources.HTTP.filter(x$ => x$.url.indexOf("https://api.nasa.gov/neo/rest/v1/feed") != -1).select(response$$); 
    const response$ = response$$.switch(); //flatten the stream 
    const nasa$ = response$.map(response => { 
     return response.body 
    }); 

    const sinks = { 
     DOM: nasa$.map(nasa => 
      ([nasa.near_earth_objects]).map(objects => { 
       var vdom = []; 
       //I am not very happy with this part. Can this be improved? 
       for (var key in objects) { 
        if (objects.hasOwnProperty(key)) { 
         vdom.push(objects[key].map(obj => div([ 
          h1(obj.name) 
         ]))) 
        } 
       } 
       //returning the vdom does not render on the browser. vdom is an array of arrays. How should i correct this? 
       console.log(vdom); 
       return vdom; 
      }) 
     ), 
     HTTP: request$ 
    }; 
    return sinks; 
}; 

回答

1

在概念上,要提取的nasa.near_earth_objects(即,打開的對象置於一個陣列),則該平面陣列映射到可觀察到的序列中的條目。

我假設你已經在你的項目中使用lodash(你可以不用lodash,但是你只需要手動編寫更多的膠水代碼)。我還會假設你正在導入RxJS'Observable as Rx.Observable;調整下面的名字以適應您的代碼。

可以完成使用_.toPairs(nasa.near_earth_objects)第一個任務,並通過調用.flatMap(),並返回Rx.Observable.from(near_objects)第二部分。由此產生的Observable將爲nasa.near_earth_objects中的每個鍵發射項目。每個項目將是一個數組,其中item[0]是項目的關鍵字(例如,2016-09-06)和item[1]是項目的值。

使用這個想法,你可以像更換您DOM片:

nasa$.map(nasa => _.toPairs(nasa.near_earth_objects)) 
    .flatMap(near_objects => Rx.Observable.from(near_objects)) 
    .map(near_object => div([ 
     h1(near_object[1].name) 
    ])) 
), 
+0

我做同樣的事情,但沒有flatMap,唯一的區別,掙扎頗有幾分後想通了我自己。幫助我理解我的概念。非常感謝。 – Tanmay