首页 > 解决方案 > 嵌套的 Angular 订阅未触发

问题描述

我有 3 个订阅需要订阅。但是当我运行它时,只有 1 个或 2 个触发了 3 个。我什至尝试交换订阅的顺序,最后一个仍然没有被触发。我还尝试在constructor我的角度组件和ngOnInit(). 我得到同样的回应。

尝试1:

this.n.authorizations.subscribe(x => {
    alert("1"); // ✅
    this.n.pages.subscribe(y => {
        alert("2"); // ❌
        this.n.user.subscribe(user => {
            alert("3"); // ❌
        });
    });
});

尝试2:

this.n.pages.subscribe(y => {
    alert("1"); // ✅
    this.n.authorizations.subscribe(x => {
        alert("2"); // ✅
        this.n.user.subscribe(user => {
            alert("3"); // ❌
        });
    });
});

尝试 3:

this.n.user.subscribe(user => {
    alert("1"); // ✅
    this.n.authorizations.subscribe(x => {
        alert("2"); // ✅
        this.n.pages.subscribe(y => {
            alert("3"); // ❌
        });
    });
});

我确实有这些服务的代码,但它们又长又复杂。可能与问题无关。

标签: angularrxjs

解决方案


从您遵循的方法来看,看起来任何订阅都不依赖于其他订阅。

所以在那种情况下,为什么不forkJoin把它们再subscribe加入 Observable。

import { forkJoin } from 'rxjs';
...
const combined = forkJoin(
  this.n.user,
  this.n.authorizations,
  this.n.pages
);
...
combined.subscribe(
  [user, auths, pages] => console.log(user, auths, pages),
  error => console.log(error),
  () => console.log('Combined Completed')
);

推荐阅读