LoginSignup
1
1

More than 5 years have passed since last update.

Observableのsubscribeを停止する

Posted at

view側で async pipe を通してできた実態を参照できないときに、Observablesubscribe する必要があったので、その時のことをメモ。

Observable の実態を async pipe を通して実態を参照するやり方をしていたが、それができない時にJS側で subscribe する必要があった。

qiita.html
<ng-container *ngIf="users$ | async as users">
  <ng-container *ngFor="let user of users.userInformation; let i = index">
    ...
  </ng-container>
</ng-container>

subscribe すると、画面遷移しても subscribe が残り続けてしまっていたので、Angularがディレクティブ/コンポーネントを破壊する直前に、 unsubscribe した。

qiita.ts
import { Component, OnDestroy } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { Observable, Subscription } from 'rxjs';
import { UsersStateService, IUsers } from "../../states/users-state.service";

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnDestroy {
  // ① Subscriptionをインスタンス化
  public subscription = new Subscription();
  public users$: Observable<IUsers>;

  constructor(
    public usersState: UsersStateService
    private route: ActivatedRoute
  ) {
    this.queryParams = this.route.snapshot.queryParams;

    this.usersState.fetch();

    // ② subscribeするときに、subscribeの返り値のSubscriptionをadd()しておく
    this.subscription.add(this.users$.subscribe((user) => {
      if (user) {
        this.user = user.userInformations.find((user) => {
          return user.userId === parseInt(this.queryParams.userId, 10);
        });
      }
    }));
  }

  public ngOnDestroy(): void {
    // ③ Componentが破棄されるタイミングで、subscriptionを全てunsubscribeする
    this.subscription.unsubscribe();
  }
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1