Angular: Service Observable doesn't fire in co

2020-05-06 17:13发布

问题:

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.

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

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);
  }
});
} 

Component

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

    }
  }
}

回答1:

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.