【发布时间】:2019-11-16 13:15:22
【问题描述】:
我正在尝试在 ngrx Effect 中进行两次 http 调用。假设我有 cmets 要取。它首先调用以获取最新评论并检查它是否已经存在于 UI 上,如果没有,我会再次调用并获取所有 cmets。这在连续轮询中运行。这是我的代码。我现在正在学习 angular 和 Observable 是一种混乱。
@Effect()
fetchAllComments: Observable<any> = this.actions$.pipe(
ofType(commentsActions.FETCH_ALL_COMMENTS),
withLatestFrom(this._store),
mergeMap(([action, state]) => {
return this._http.get(`${this.baseUrl}/comments/latest`)
.pipe(
catchError(error => {
console.log(error);
return this._error.handle(error, new commentsActions.FetchAllCommentsError)
}))
.subscribe(comment => {
console.log("Response from server", comment);
if (!!comment['id'] && state.comment.comments.every(n => n.id !== comment['id'])) {
console.log("making call to fetch api ");
return this._http.get(`${this.baseUrl}/comment`)
.pipe(
map((comments: any) => new commentsActions.FetchAllCommentsComplete(comments.message)),
catchError(error => {
return this._error.handle(error, new commentsActions.FetchAllCommentsError);
}));
} else {
console.log("returning mock");
return of(state.comment.comments);
}
})
}));
这是正确的方法吗?我收到一堆以core.js:15724 ERROR TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.开头的错误
谢谢
【问题讨论】:
-
是的,这可能是最好的方法。我正在努力添加这个小功能。基本上我来自 AngularJS 背景,到目前为止只使用过 Promise。
-
响应式编程是近来编程最伟大的进步之一。 RxJs 是响应式编程的 JS 实现,Angular 就是基于它构建的。我从 AngularJs 跳入 Angular,对 RxJs 并没有很好的理解,希望几年前有人给我这个建议。确保在充分了解 RxJs 的基础知识之前不要使用任何 Angular,如果我这样做,我在前几个项目中编写的代码会大不相同。
标签: angular typescript observable angular7 ngrx-store