如何在重建内部可观察对象的地方创建RxJS链式可观察对象

时间:2020-09-10 09:43:18

标签: angular 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)
  }
}

外部可观察到的触发更新,但是内部未触发

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

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)
  )
)

0 个答案:

没有答案