观察递归列表或面包屑

时间:2018-11-23 12:12:16

标签: angular rxjs observable

我有一个递归异步功能,可建立面包屑或建立论坛的路径,但我还没有弄清楚如何观察面包屑本身?这样便可以观察到构成面包屑的所有论坛,因此,如果其中任何一个更改,整个面包屑将再次被订阅。如果当用户删除论坛时parentId之一发生更改,从而断开了链接,则会发生这种情况。我需要一个可观察的热点吗?

我认为我现在必须更改它:

const parentForum =等待那.forumsAllService.getForumFromPromise(forumId);

以便我观察它,但是如何以单个观察者的身份观察所有论坛?

const parentForum =等待那.forumsAllService.getForumFromObservable(forumId);

我必须更改代码的哪些部分?

// routine to fetch the parent forums that make up the breadcrumb to the child.
private getBreadcrumbs (parentForumId): Promise<any[]> {
    return new Promise<any[]>((resolve, reject) => {
      const that = this;

      let breadcrumbs: any[] = [];

      // fetch parent forum
      const getBreadcrumbFragment = async function (forumId) {
        const parentForum = await that.forumsAllService.getForumFromPromise(forumId);

        if (parentForum){
          // store forum and check if it has a parent of its own, store its id as the nextPage
          return {
            data: parentForum,
            nextPage: parentForum && parentForum.parentId && parentForum.parentId.length > 0 ? parentForum.parentId : undefined
          };
        }
        else {
          return {
            data: null,
            nextPage: undefined
          };
        }
      };

      // recursive routine to build breadcrumb
      const getBreadcrumb = async function (forumId) {
        const fragment = await getBreadcrumbFragment(forumId)

        // store our crumbs
        if (fragment && fragment.data)
          breadcrumbs.push(fragment.data);

        if (fragment.nextPage) { // we still have another parent child relationship to fetch
          return await getBreadcrumb(fragment.nextPage);
        } else {
          return breadcrumbs.reverse(); // finish, put list the right way around
        }
      }

      // initialize breadcrumb
      getBreadcrumb(parentForumId);

      // return our results
      resolve(breadcrumbs);
    });
}

// *****************************************************
// this is how i eventually call the recursive function
// *****************************************************
if (forum.parentId && forum.parentId.length > 0){
    console.log('fetching breadcrumbs');
    this._breadcrumbSubscription = Observable.fromPromise(this.getBreadcrumbs(forum.parentId))
        .subscribe(breadcrumbs => {
        this.breadcrumbs = of(breadcrumbs);
    });
}
else {
    console.log('not fetching breadcrumbs');
    this.breadcrumbs = of([]);
}

0 个答案:

没有答案