【问题标题】:Using observable filter in Angular 2在 Angular 2 中使用可观察过滤器
【发布时间】:2018-07-10 15:52:11
【问题描述】:

我正在尝试过滤 Observable 并在我的视图中循环使用它,但它不会呈现。

this.client_comments$ = this.comments$.filter(comment => comment.commentable_type == 'Client')

comments$ 在哪里:

comments = new BehaviorSubject([]);
this.comments.next(this.client.comments) // this.client.comments is an array of comment objects
this.comments$ = this.comments.asObservable()

结果是正确的,但是当我尝试使用异步管道渲染它时,什么都没有显示:

<p *ngFor="let comment of client_comments$ | async">{{ comment.body }}</p>

在查看 devtools 中的对象后,我发现似乎有一个嵌套的 observable(2 个来源):

client_comments$: Observable
    operator: FilterOperator {predicate: ƒ, thisArg: undefined}
    source: Observable
        source: BehaviorSubject
            ...
            value: (...)

而我的其他可观察对象具有以下结构(1 个来源):

comments$: Observable
    operator: FilterOperator {predicate: ƒ, thisArg: undefined}
    source: BehaviorSubject
        ...
        value: (...)

有没有办法让我的 client_comments$ 在 n async 管道中工作? 请注意client_comments$ observable 数组包含所有需要的值

这是fiddle showing the structure change you can inspect in the console

这是fiddle showing the issue with the async pipe in the view

【问题讨论】:

  • comments$ 是什么?
  • comments$: Observable&lt;any[]&gt;。这是一个 Observable 列表
  • 过滤comments$之后好像改变了observable的结构
  • 你能展示创建comments$的代码吗?
  • 我已经在上面添加了

标签: angular asynchronous filter rxjs observable


【解决方案1】:

我看到你没有投票给我,但你的问题是你不了解不同的数据类型

在你的小提琴中,替换:

filteredComments$ = this.comments$.filter(function(comment) {
    comment.commentable_type == 'Client'
})

与`;

filteredComments$ = this.comments$.map(function(ARRAY) {
  return ARRAY.filter(function(comment) {
    return comment.commentable_type == 'Client'
  })
});

然后看看你自己...

原帖:


看起来您尝试过滤的不是发射的项目,而是要返回的发射项目 - comment =&gt; comment.commentable_type == 'Client'

所以上面的内容等价于[array of objects emitted by your subject].commentable_type == 'Client',对于任何发射的项目来说都是不正确的。而是尝试:

this.client_comments$ = this.comments$.map(item => item.filter(comment => comment.commentable_type == 'Client'))

【讨论】:

  • 过滤器工作正常,并给了我正确的值,所以情况并非如此。唯一不起作用的是返回项目的结构
  • @Jeremy Thomas - 这里的this.comments$.filter(comment =&gt; 你的comment 是一个数组。所以你不能通过引用整个数组来过滤它。您必须遍历其项目并过滤它们。你怎么知道过滤器有效?你试过我写的吗?
  • 我以为 rxjs filter 函数被赋予了一个可观察数组,谓词是数组中的一个对象 const source = Rx.Observable.from([1, 2, 3, 4, 5]); const example = source.filter(num =&gt; num % 2 === 0);
  • ...不,它不适用于您的解决方案。我找到了解决方法,所以它并不重要
  • @JeremyThomas Observable.from 将从可迭代项中创建一个序列——例如,它将一次发出一个奇异值。但在你的情况下 (this.cmets$.filter(comment => ...) 就像 J.D 说的那样,它将是一个数组
猜你喜欢
  • 2020-09-10
  • 1970-01-01
  • 2018-12-22
  • 2016-11-19
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
相关资源
最近更新 更多