簡體   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