Angular:组件中不会触发Service Observable

编程入门 行业动态 更新时间:2024-10-25 20:22:31
本文介绍了Angular:组件中不会触发Service Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的效果,调用服务中的方法以显示对话.对话完成后,结果可观察到.

my effects when erring, calls a method in service to display a dialogue. When dialogue completes, it puts result into an observable.

我有一个组件正在监听该服务中的可观察对象.问题在于,该组件第一次监听服务,然后什么也没听到.

I have a component that is listening to that observable inside that service. Problem is that the component listens to service the very first time and then it doesn't hear anything.

我正在设置该主题以避免出现第一次this.errorService.errorExist $不返回任何内容的错误消息.

I'm setting that subject to avoid getting the error message that for first time this.errorService.errorExist$ is not returning anything.

ErrorService

ErrorService

private errorExist = new Subject<boolean>(); errorExist$ = this.errorExist.asObservable(); constructor(public dialog: MatDialog) { this.errorExist.next(false); } handleError() { const dialogRef = this.dialog.open(ConfirmDialogComponent, { data: { title: 'Error Occurred', btn: 'OKAY' } }); dialogRef.afterClosed().pipe(take(1)).subscribe( (result: boolean) => { console.log('inside the closed and result is: ', result); if (result) { this.errorExist.next(true); } }); }

组件

constructor(errorService: ErrorService) { } private subscribeToError() { this.errorService.errorExist$.pipe(takeUntil(this.destroyed$)).subscribe((x: boolean) => { console.log('this does not print'); if (x) { } } }

推荐答案

我建议使用rxjs库.

I would recommend the rxjs library.

将错误存在的主题更改为行为主题.

Change the errorexist's Subject to a Behaviour subject.

行为科目是可以多次收听并且具有起始值的科目.

Behaviour subject is such a subject which can be listened at multiple times and also has a starting value.

更多推荐

Angular:组件中不会触发Service Observable

本文发布于:2023-11-22 23:35:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619350.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   Angular   Observable   Service

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!