RxJS 6获取Observable数组的过滤列表 [英] RxJS 6 get a filtered list of array of Observable

查看:106
本文介绍了RxJS 6获取Observable数组的过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ThreadService类中,我有一个函数 getThreads(),该函数为我所有线程提供了 Observable< Thread []> .

In my ThreadService class, I have a function getThreads() that return me a Observable<Thread[]> with all my threads.

现在,我想使用另一个函数版本,其线程由选定主题过滤:函数 getSelectedThemeThreads(theme:Theme).

Now, I would like to have another version of my function with my threads filtered by a selected theme : function getSelectedThemeThreads(theme: Theme).

我尝试使用运算符 map filter ,但出现以下错误消息类型'Thread []上不存在属性'theme'.

I tried with the operators map and filter but I have the following error message Property 'theme' does not exist on type 'Thread[].

在我正在处理的代码下面:

Below the code I am working on :

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Thread } from '../models/thread.model';
import { Theme } from '../models/theme.model';

@Injectable({
  providedIn: 'root'
})
export class ThreadService {
  private threadsUrl = 'api/threads';

constructor(private http: HttpClient) { }

getThreads(): Observable<Thread[]> {
  return this.http.get<Thread[]>(this.threadsUrl);
}

getSelectedThemeThreads(): Observable<Thread[]> {
  return this.http.get<Thread[]>(this.threadsUrl).pipe(
    map(threads => threads),
    filter(thread => thread.theme.id === theme.id)
  );
}

预先感谢您的帮助.

推荐答案

我以主要思想是在 map()中进行过滤,因为过滤器将获得对象数组.

The main idea is to filter in the map() as the filter will get an array of objects.

getSelectedThemeThreads(theme: string): Observable<Flower[]> {
    return this.http.get<Flower[]>(this.threadsUrl).pipe(
      map(result =>
        result.filter(one => one.theme === theme)
      )
    )
  }

这篇关于RxJS 6获取Observable数组的过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆