首页 > 解决方案 > 如何在内部可观察对象被重建的地方创建 RxJS 链式可观察对象

问题描述

我一直在努力解决我无法弄清楚的 RxJS 问题。

链式(完成)可观察模式

// pseudocode

http-request -> 
  do-another-http-request -> 
    returned combined result

// - chain is always triggered from the outer observable
// - chain completes after each cycle

链式(非完成)可观察模式:

我要解决的问题略有不同,因为它没有完成,但它具有相同的链式可观察性质。

blog-post_with_category:
  -> on-category-id-change
    -> return observable of category from datastore

// As shown above, the blog post could either be switched
// to a new category (category_id:6 -> category_id:7)
//
// OR the category itself could change in the datastore i.e. a
// category with a particular id could have an updated 
// label (id:3, label:'Sailing' -> id:3, label:'Nautical')

当放入代码中时,该模式不起作用:


export class BlogPostClass{

  postData: PostData
  category$: Observable<Category | undefined>
  private categoryId$: Subject<string>

  constructor(postData:PostData, categoriesQuery: CategoriesService){

    // Create an observable for the category ID
    this.categoryId$ = new Subject()

    // update the data & trigger ID to emit
    this.update(postData)
    

    // Chained observable  ------------------------
    this.category$ = this.categoryId$.pipe(
      mergeMap((newCategoryId:string) => 
        // observable of category from datastore
        this.categoriesQuery.selectEntity(newCategoryId)
      )
    )
    //-----------------------------------------------
  }

  // ensure that new category ID is emitted on update
  update(postData:PostData):void{
    this.postData = postData
    this.categoryId$.next(postData.category_id)
  }
}

外部 observable 触发更新,但内部不触发

订阅生成的链式观察者表明它会在外部观察者更新时更新,但在内部观察者更新时不会更新:

post = new BlogPost(postData)
post.category$.subscribe((newCategory) =>
  console.log('label: ' + newCategory.label)
)

post.update( {category_id: newValue } )
=> label: new category label

post.category.update( {label: 'different label'} )
// nothing is printed into the console

少了什么东西?

this.category$ = this.categoryId$.pipe(
  mergeMap((newCategoryId:string) => 
    this.categoriesQuery.selectEntity(newCategoryId)
  )
)

标签: angularrxjs

解决方案


推荐阅读