从http数据而不是单个用户显示多个用户

时间:2016-02-18 20:48:04

标签: javascript reactive-programming rxjs cyclejs

我正在尝试修改以下代码,以便从http接收一组用户并显示所有这些用户。此代码仅接收并显示单个用户。

import Cycle from '@cycle/core';
import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom';
import {makeHTTPDriver} from '@cycle/http';

function main(sources) {
  const USERS_URL = 'http://jsonplaceholder.typicode.com/users/';
  const getAllUsers$ = sources.DOM.select('.get-all').events('click')
    .map(() => {
      return {
        url: USERS_URL + 1,
        method: 'GET'
      };
    });

  const user$ = sources.HTTP
    .filter(res$ => res$.request.url.indexOf(USERS_URL) === 0)
    .mergeAll()
    .map(res => res.body)
    .startWith(null);

  const vtree$ = user$.map(user =>
    div('.users', [
      button('.get-all', 'Get all users'),
      user === null ? null : div('.user-details', [
        h1('.user-name', user.name),
        h4('.user-email', user.email),
        a('.user-website', {href: user.website}, user.website)
      ])
    ])
  );

  return {
    DOM: vtree$,
    HTTP: getAllUsers$
  };
}

const drivers = {
  DOM: makeDOMDriver('#app-main'),
  HTTP: makeHTTPDriver(),
};

Cycle.run(main, drivers);

1 个答案:

答案 0 :(得分:2)

您应该为多个用户执行一个请求,然后迭代它们:

获取所有用户:

// rather than getting just user 1
url: USERS_URL,

更新此信息流:

const users$ = sources.HTTP // users (plural)
.filter(res$ => res$.request.url.indexOf(USERS_URL) === 0)
.mergeAll()
.map(res => res.body)
.startWith([]); // start with an empty array

为所有用户生成标记:

users.map(user => 
  div('.user-details', [
    h1('.user-name', user.name),
    h4('.user-email', user.email),
    a('.user-website', {href: user.website}, user.website)
  ])
)

这是完整的,有效的代码:

function main(sources) {
  const USERS_URL = 'http://jsonplaceholder.typicode.com/users/';
  const getAllUsers$ = sources.DOM.select('.get-all').events('click')
    .map(() => {
      return {
        url: USERS_URL,
        method: 'GET'
      };
    });

  const users$ = sources.HTTP
    .filter(res$ => res$.request.url.indexOf(USERS_URL) === 0)
    .mergeAll()
    .map(res => res.body)
    .startWith([])

  const vtree$ = users$.map(users => {
    return div('.users', [
      button('.get-all', 'Get all users'),
      ...users.map(user => 
        div('.user-details', [
          h1('.user-name', user.name),
          h4('.user-email', user.email),
          a('.user-website', {href: user.website}, user.website)
        ])
      )
    ])
  });

  return {
    DOM: vtree$,
    HTTP: getAllUsers$
  };
}