我對cyclejs和rxjs一般都很陌生,希望有人能幫我解決我的問題。 我想爲我的理解構建一個演示應用程序,並堅持在DOM上呈現JSON對象。在RxJS中處理JSON對象
- 我的演示應用程序在過去7天內調用NASA附近的地球對象API並嘗試顯示它們。
- 底部有一個
Load More
按鈕,點擊後會加載前7天的數據(Today - 7
uptoToday - 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;
};
我做同樣的事情,但沒有flatMap,唯一的區別,掙扎頗有幾分後想通了我自己。幫助我理解我的概念。非常感謝。 – Tanmay