这是我的epic,它不能工作。
export const getUserDetails = (action$) =>
action$.pipe(
ofType(GET_USER_DATA),
mergeMap(async (action) => {
const readData = firebaseApp.database().ref(`users/${id}`)
const myData = await readData.once('value').then((snapshot) => {
const data = snapshot.val()
// console.log(data) this works correctly
return data
})
return [fetchDataFulfilled(myData)]
}),
catchError((e) =>
of({
type: 'FAILED_TO_FETCH_DATA',
e,
}),
),
)
当我在 await 中记录数据时,数据是存在的,但由于某些原因,我不能将数据传递给动作来实现它。
错误是说。Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
但这是中间件?
所以我的主要问题是,我如何等待firebase履行,然后正确发送数据到我的epic?
我认为你必须用以下方法将Promise转换为observable。rxjs
从 经营者
import { from } from 'rxjs';
const fetchUserFulfilled = payload => ({ type: `FETCH_USER_FULFILLED`, payload });
const failedFetch = error => ({type: 'FAILED_TO_FETCH_DATA', error});
const getData = (id) => from(firebaseApp.database()
.ref(`users/${id}`).
.once('value')
.then((snapshot) => snapshot.val()))
export const getUserDetails = (action$) =>
action$.pipe(
ofType(GET_USER_DATA),
mergeMap((action) => getData(id)),
map(fetchUserFulfilled)
catchError((error) => of(failedFetch(error)))
)