异步管道订阅是否仍然取消订阅离子路由?

发布于 2025-02-11 22:24:06 字数 1576 浏览 1 评论 0原文

背景:我目前正在使用一种使用Promises的移动应用程序,并且正在探索RXJS的可观察到替换所有现有的Promise API调用。 我对异步管的理解是,当触发ngondestroy时,它会自动取消订阅。因为我正在使用离子路由它不会触发ngondestroy IT只能触发ionviewWillleave我导航到另一页。

代码: 我在HTML模板中实现了一个看起来像这样的异步管道:

 <ng-container *ngIf="accounts$ | async as accounts; else loadingData">
  <app-account-card *ngFor="let account of accounts" [account]="account"></app-account-card>
</ng-container>

<!-- SKELETON -->
<ng-template #loadingData>
  <app-skeleton-account-card></app-skeleton-account-card>
</ng-template>

我有一个account.service.ts返回observable&lt; account []&gt; gt;

getAccountsObserver(): Observable<Account[]> {
try {
        return from(this.getSessionID()).pipe(
            switchMap(sessionId => this.http.get<Account[]>(`${URLS.accounts}${ENDPOINTS.accBalance}${sessionId}`))
        );
    } catch (e) {
        return null;
    }
}

for My < code> account.component 我只是声明了变量帐户$

accounts$: Observable<Account[]>;

  constructor(
    private accountProvider: AccountProvider
  ) {}

  ngOnInit() {
    this.accounts$ = this.accountProvider.getAccountsObserver();
  }

问题: async管道仍然取消订阅吗?如果没有,我该如何取消订阅?异步管仍然是显示API数据的最佳方法,还是我需要在情况下找到其他方法?

BACKGROUND: I'm currently working on a mobile app that uses Promises and I'm exploring RxJS' Observables to replace all existing promise API calls.
My understanding for async pipe is that it automatically unsubscribes when the ngOnDestroy is triggered. Since I am using Ionic Routing it does not trigger the ngOnDestroy it can only trigger ionViewWillLeave once I navigated to other page.

CODE:
I implemented an async pipe in my html template that looks like this:

 <ng-container *ngIf="accounts$ | async as accounts; else loadingData">
  <app-account-card *ngFor="let account of accounts" [account]="account"></app-account-card>
</ng-container>

<!-- SKELETON -->
<ng-template #loadingData>
  <app-skeleton-account-card></app-skeleton-account-card>
</ng-template>

I have an account.service.ts that returns an Observable<Account[]>:

getAccountsObserver(): Observable<Account[]> {
try {
        return from(this.getSessionID()).pipe(
            switchMap(sessionId => this.http.get<Account[]>(`${URLS.accounts}${ENDPOINTS.accBalance}${sessionId}`))
        );
    } catch (e) {
        return null;
    }
}

For my account.component I simply declared a variable accounts$:

accounts$: Observable<Account[]>;

  constructor(
    private accountProvider: AccountProvider
  ) {}

  ngOnInit() {
    this.accounts$ = this.accountProvider.getAccountsObserver();
  }

QUESTION: Does the Async Pipe still unsubscribes? If no, how can I unsubscribe to it? Is Async Pipe still a best way to display a data from the API or do I need to find a different approach in my case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文