我刚刚开始学习@ ngrx/store和@ ngrx.effects,并在我的Angular/Ionic应用程序中创建了我的第一个效果.它第一次运行正常但如果我再次将事件发送到商店(即再次单击按钮),则没有任何反应(没有进行网络调用,控制台日志中没有任何内容).有什么明显的东西我做错了吗?这是效果:
@Effect() event_response$ = this.action$
.ofType(SEND_EVENT_RESPONSE_ACTION)
.map(toPayload)
.switchMap((payload) => this.myService.eventResponse(payload.eventId,payload.response))
.map(data => new SentEventResponseAction(data))
.catch((error) => Observable.of(new ErrorOccurredAction(error)));
Run Code Online (Sandbox Code Playgroud)
谢谢
car*_*ant 23
听起来好像正在发生错误.在这种情况下,返回的observable中的动作catch将被发送到效果的流中,然后效果将完成 - 这将阻止在发出错误动作后运行效果.
移动map并catch进入switchMap:
@Effect() event_response$ = this.action$
.ofType(SEND_EVENT_RESPONSE_ACTION)
.map(toPayload)
.switchMap((payload) => this.myService
.eventResponse(payload.eventId, payload.response)
.map(data => new SentEventResponseAction(data))
.catch((error) => Observable.of(new ErrorOccurredAction(error)))
);
Run Code Online (Sandbox Code Playgroud)
如果发生错误,catch在内部进行组合switchMap将阻止效果完成.
您必须map()搬入catchError()如下swithchMap()
@Effect()
public event_response$ = this.action$.pipe(
ofType(SEND_EVENT_RESPONSE_ACTION),
switchMap((payload) => {
return this.myService.eventResponse(payload.eventId,payload.response).pipe(
map((data: DataType) => new SentEventResponseAction(data)),
catchError((error) => Observable.of(new ErrorOccurredAction(error)))
})
);
);
Run Code Online (Sandbox Code Playgroud)
请注意,evetResponse()内部方法myService应该返回一个可观察的对象,以便以后使用管道。如果服务中的方法返回Promise,您可以通过在 rxjs 包中使用 将其转换为可观察对象,from如下所示:
import { from } from 'rxjs';
...
const promise = this.myService.eventResponse(payload.eventId,payload.response);
const observable = from(promise);
return observable.pipe(...
Run Code Online (Sandbox Code Playgroud)
有关更多详细说明,请查看此链接
| 归档时间: |
|
| 查看次数: |
2543 次 |
| 最近记录: |