简体   繁体   English

在 Angular 服务中取消订阅 observable

[英]Unsubscribe observable in an Angular service

I want to unsubscribe an observable in an angular service once a certain state is present.一旦存在某个 state,我想取消订阅 angular 服务中的 observable。 The unsubscribe should be executed within the subscription.取消订阅应该在订阅中执行。 Unfortunately the code below does not work.不幸的是,下面的代码不起作用。

@Injectable()
export class CartManagementUsecase {
  private unsubscribe = new Subject();

  public streamSession(): void {
    this.adapter
        .streamSession()
        .pipe(takeUntil(this.unsubscribe))
        .subscribe((session) => {
          if(session.session_state === SessionState.CLOSED) {
            this.unsubscribe.unsubscribe();
          }
    });
  }
}

You need to call complete on your subject for takeUntil to unsubscribe to the observable.您需要在您的主题上调用complete以便takeUntil取消订阅 observable。

@Injectable()
export class CartManagementUsecase {
  private unsubscribe = new Subject();

  public streamSession(): void {
    this.adapter
        .streamSession()
        .pipe(takeUntil(this.unsubscribe))
        .subscribe((session) => {
          if(session.session_state === SessionState.CLOSED) {
            this.unsubscribe.complete();
          }
    });
  }
}

I would recommend you to take events untill closed is come.我建议您参加活动,直到closed no subject would be required不需要任何主题

public streamSession(): void {
    this.adapter
        .streamSession()
        .pipe(takeWhile(session => session.session_state != SessionState.CLOSED))
        .subscribe((session) => {
          // do something that is required
        });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM