[英]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
所以我希望我的例子能幫助你理解of
和from
之間的區別。
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.