如何在角度6中将any []转换为observable <any []>

时间:2018-08-18 10:46:13

标签: angular angular5 angular6

我有一个变量countryList : any[],其中包含以下数据:

[
  {"countrycode":"SH","countryname":"Saint Helena"},
  {"countrycode":"KN","countryname":"Saint Kitts and Nevis"},   
  {"countrycode":"LC","countryname":"Saint Lucia"},   
  {"countrycode":"IS","countryname":"Iceland"}, 
  {"countrycode":"IN","countryname":"India"},  
  {"countrycode":"ID","countryname":"Indonesia"},  
  {"countrycode":"IR","countryname":"Iran (Islamic Republic of)"},   
  {"countrycode":"IQ","countryname":"Iraq"},    
  {"countrycode":"IE","countryname":"Ireland"},    
  {"countrycode":"IM","countryname":"Isle of Man"}, 
  {"countrycode":"IL","countryname":"Israel"}, 
  {"countrycode":"SH","countryname":"Saint Helena"},
  {"countrycode":"KN","countryname":"Saint Kitts and Nevis"}, 
  {"countrycode":"LC","countryname":"Saint Lucia"},
  {"countrycode":"ZM","countryname":"Zambia"},
  {"countrycode":"ZW","countryname":"Zimbabwe"}
]

我想将其转换为可观察的

如何执行此操作?

4 个答案:

答案 0 :(得分:1)

如果您使用的是rxjs 6,则可以简单地使用:

import { of } from 'rxjs';

// ...

let obs = of([
     {"countrycode":"SH","countryname":"Saint Helena"},
     {"countrycode":"KN","countryname":"Saint Kitts and Nevis"},
     // etc... 
])

如果您使用的是旧版本,请将of替换为Observable.of

答案 1 :(得分:1)

仅使用of中的rxjs运算符,像这样:return of(countryList)

答案 2 :(得分:1)

使用of以{6角的角度返回observable

import { of } from 'rxjs';

someFunction(){
    return of([
        { "countrycode": "SH", "countryname": "Saint Helena" }, 
        { "countrycode": "KN", "countryname": "Saint Kitts and Nevis" }, 
        { "countrycode": "LC", "countryname": "Saint Lucia" }, 
        { "countrycode": "IS", "countryname": "Iceland" }, 
        { "countrycode": "IN", "countryname": "India" }, 
        { "countrycode": "ID", "countryname": "Indonesia" }, 
        { "countrycode": "IR", "countryname": "Iran (Islamic Republic of)" }, 
        { "countrycode": "IQ", "countryname": "Iraq" }, 
        { "countrycode": "IE", "countryname": "Ireland" }, 
        { "countrycode": "IM", "countryname": "Isle of Man" }, 
        { "countrycode": "IL", "countryname": "Israel" }, 
        { "countrycode": "SH", "countryname": "Saint Helena" }, 
        { "countrycode": "KN", "countryname": "Saint Kitts and Nevis" }, 
        { "countrycode": "LC", "countryname": "Saint Lucia" }, 
        { "countrycode": "ZM", "countryname": "Zambia" }, 
        { "countrycode": "ZW", "countryname": "Zimbabwe" }
    ])
}

答案 3 :(得分:0)

如果要使用rxjs包,可以将<[]转换为Observable(any []),可以使用功能

在component.ts中

import { of } from 'rxjs';

// Other imports

let observableData = of([
{"countrycode":"SH","countryname":"Saint 
Helena"},
{"countrycode":"KN","countryname":"Saint 
Kitts and Nevis"},
{"countrycode":"Ky","countryname":"Saint 
Kitt and Nevis"}

])

请参阅此link