首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何处理可观察对象的可选参数?

如何处理可观察对象的可选参数?
EN

Stack Overflow用户
提问于 2018-06-13 02:43:44
回答 2查看 490关注 0票数 0

我有一个Angular组件,它使用service.getItems从服务中获取数据。有时,服务调用是简单的,在其他情况下,需要一个过滤器。可以通过零部件特性filter设置此过滤器。

我确信我从根本上遗漏了一些东西,但我不能让它正常工作。我可以让它接受筛选器,或者忽略筛选器,但不会对筛选器的存在做出反应。

有什么建议可以修改下面的代码来实际工作吗?

代码语言:javascript
运行
复制
@Component({}
  selector: 'my-component',
  template: `
    <!-- Items are shown async -->
    {{ items | async }}
  `
})
export class MyComponent {

  //////////////////////////////////////////////////////////////////
  // Initialize the filter observable with a null value
  //////////////////////////////////////////////////////////////////
  constructor(private service) {
    this.filter = null;
  }

  //////////////////////////////////////////////////////////////////
  // Filter observable to hookup the filter value to the service
  //////////////////////////////////////////////////////////////////
  filter$: Subject<Filter> = new Subject<Filter>();

  //////////////////////////////////////////////////////////////////
  // Service call to fetch items
  //////////////////////////////////////////////////////////////////
  items$: Observable<any[]> = this.filters$.pipe(
    switchMap(filter => this.service.getItems(filter));
  );

  //////////////////////////////////////////////////////////////////
  // Allow filter with
  // <my-component [filter]="myFilter">
  //////////////////////////////////////////////////////////////////
  @Input()
  set filter(filter: Filter) {
    this.filter$.next(filter);
  }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50823818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档