2017-05-31 50 views
0

我遇到了史詩般的問題,請幫我找出我出錯的地方。謝謝!redux-observable:操作必須是普通對象。使用自定義中間件進行異步操作

下面的代碼使我的錯誤:

const loginEpic = (action$) => 
 
    action$ 
 
    .ofType('LOGIN') 
 
    .switchMap(() => { 
 
     return Observable.fromPromise(loginService()) 
 
     .map((result) => { 
 
      return Observable.of({ 
 
      payload: result, 
 
      type: types.loginCompleted, 
 
      }); 
 
     }) 
 
     .catch((error) => { 
 
      return Observable.of({ 
 
      payload: error, 
 
      type: types.loginFailed, 
 
      }); 
 
     }); 
 
    });

這裏是我的configureStore文件:

const epicMiddleware = createEpicMiddleware(rootEpic); 
 

 
// Ref: https://redux-observable.js.org/docs/recipes/HotModuleReplacement.html 
 
if (module.hot) { 
 
    module.hot.accept('./epic',() => { 
 
    const nextEpic = require('./epic'); 
 
    epicMiddleware.replaceEpic(nextEpic); 
 
    }); 
 
} 
 

 
const configureStore =(): Store<any> => { 
 

 
    const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(epicMiddleware))); 
 
    if (module.hot) { 
 
    module.hot.accept('./reducer',() => { 
 
     const nextReducer = require('./reducer').default; 
 
     store.replaceReducer(nextReducer); 
 
    }); 
 

 
    return store; 
 
    } 
 
};

回答

3

我相信你必須從map()內掉落Observable.of(...)編輯 - 感謝paulpdaniels:但不是catch())方法,因爲這樣你是返回一個可觀察的觀察量 - 見下面的簡化代碼:

Observable.fromPromise(...) 
    .map(result => Observable.of(...)) // maps an object to an observable 

整個代碼應該是:

const loginEpic = (action$) => 
    action$ 
    .ofType('LOGIN') 
    .switchMap(() => { 
     return Observable.fromPromise(loginService()) 
     .map((result) => { 
      return { 
      payload: result, 
      type: types.loginCompleted, 
      }; 
     }) 
     .catch((error) => { 
      return Observable.of({ 
      payload: error, 
      type: types.loginFailed, 
      }); 
     }); 
    }); 
+2

你衝出,正確的從'map'刪除,但'catch'需要一個'Observable'回報。 – paulpdaniels

+0

@ paulpdaniels是的,絕對正確,謝謝你的糾正! –

+0

哦,我沒認出來。謝謝;) – hxuanhung

相關問題