繁体   English   中英

如何从可观察到的 rxjs 返回一个数组?

[英]How to return an array from rxjs observable?

我从简单地拉入一个数组并映射值开始,设置为 state,然后使用传统的反应和 javascript 方法在屏幕上显示

现在我想用 rxjs 重建它

{
    "countriesList": [
        {
            "name": "Australia"
        },
        {
            "name": "Austria"
        },
        {
            "name": "Beligum"
        },
        {
            "name": "Belize"
        },
        {
            "name": "Brazil"
        },
        {
            "name": "Cameroon"
        },
        {
            "name": "Denmark"
        }
    ]
}


const countries$ = of(countriesList) // this returns the array above

但是当我开始输入值时,我想过滤这个列表。 通常我会构建一个 function,然后根据输入进行过滤。 但努力用 rxjs 复制这个

我尝试了以下方法并不断获得countries.map地区。map 不是 function

return countries$.subscribe((countries) => countries)

我也试过这个:

countries$.pipe(map((country) => country.filter((ctry) => ctry.name.toLowerCase().startsWith(e.target.value))))

我想 map 然后过滤并返回以键入的字母开头的值

没有真正掌握这个

有任何想法吗?

好的,对于初学者来说,我最近正在尝试学习rxjs所以我希望我的例子能帮助你理解offrom之间的区别。

回顾一下“创作者”作品也很不错。

const { from, of, pipe } = rxjs;
const { map, filter } = rxjs.operators;

console.clear();

const countries = [
        {
            "name": "Australia"
        },
        {
            "name": "Austria"
        },
        {
            "name": "Beligum"
        },
        {
            "name": "Belize"
        },
        {
            "name": "Brazil"
        },
        {
            "name": "Cameroon"
        },
        {
            "name": "Denmark"
        }
    ];

const countriesFrom$ = from(countries);
const countriesOf$ = of(countries);

console.log("----stream from----")
countriesFrom$.subscribe(val => console.log(val));

console.log("----stream of----")
countriesOf$.subscribe(val => console.log(val));

const countries$ = from(countries);

console.log('----filtering----');

countries$.pipe(
  filter(country => country && country.name && country.name.startsWith('A')),
  map(console.log)
).subscribe()

基本上of from不同,它不做任何展平,并将每个参数作为单独的下一个通知整体发出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM