【问题标题】:RxJS and redux-observable: delay(time) is not applied correctly after mapTo()RxJS 和 redux-observable:在 mapTo() 之后没有正确应用延迟(时间)
【发布时间】:2017-01-20 18:39:34
【问题描述】:

我正在尝试使用 payload.type = 'observable' 发送 'SET_MIDDLEWARE_TYPE' 操作,等待 5 秒,然后进行 API 调用。目前,未调度 SET_MIDDLEWARE_TYPE 操作。如果我删除延迟和 mergeMap,它会调度该操作。

预期: FETCH_USER_WITH_OBSERVABLE_REQUEST --> SET_MIDDLEWARE_TYPE (等待 5 秒) --> FETCH_USER_WITH_OBSERVABLE_SUCCESS

实际: FETCH_USER_WITH_OBSERVABLE_REQUEST --> (等待 5 秒) --> FETCH_USER_WITH_OBSERVABLE_SUCCESS

我怎样才能获得预期的行为?

代码:

import { Observable } from 'rxjs';
import { githubApi } from './api';

const githubEpic = action$ =>
 // Take every request to fetch a user
  action$.ofType('FETCH_USER_WITH_OBSERVABLES_REQUEST')
    .mapTo(({ type: 'SET_MIDDLEWARE_TYPE', payload: { type: 'observable'} }))
    // Delay execution by 5 seconds
    .delay(5000)
    // Make API call
    .mergeMap(action => {
      // Create an observable for the async call
      return Observable.from(githubApi.getUser('sriverag'))
        // Map the response to the SUCCESS action
        .map((result) => {
        return {
          type: 'FETCH_USER_WITH_OBSERVABLES_SUCCESS',
          payload: { result } ,
        };
      });
    });

export default githubEpic;

【问题讨论】:

    标签: rxjs redux-observable


    【解决方案1】:

    当您执行mergeMap 时,您将放弃SET_MIDDLEWARE_TYPE 操作。请注意您传递给mergeMap 的参数称为action?除非您传播它,否则它不能进一步向下游移动。

    您需要将其添加到传出流中。我建议您改为执行以下操作:

    import { Observable } from 'rxjs';
    import { githubApi } from './api';
    
    const githubEpic = action$ =>
     // Take every request to fetch a user
      action$.ofType('FETCH_USER_WITH_OBSERVABLES_REQUEST')
        .mapTo(({ type: 'SET_MIDDLEWARE_TYPE', payload: { type: 'observable'} }))
        // Delay execution by 5 seconds
        .delay(5000)
        // Make API call
        .mergeMap(action => 
          // Async call
          Observable.from(githubApi.getUser('sriverag'))
            // Map the response to the SUCCESS action
            .map(result => ({
              type: 'FETCH_USER_WITH_OBSERVABLES_SUCCESS',
              payload: { result }
            }))
            // Prepend the original action to your async stream so that it gets 
            // forwarded out of the epic
            .startWith(action)
        );
    
    export default githubEpic;
    

    【讨论】:

    • (删除了我之前的评论,误会了,这个答案确实是正确的。)
    • 感谢 paulpdaniels!
    猜你喜欢
    • 2019-05-05
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多