比较两个可观察的值并在数组中返回结果-Angular Rxjs



我正在尝试比较两个可观察的方法并返回结果。我试了一个例子,但没有得到预期的结果。我希望下面的例子(我试过的(能让问题更清楚。

GetCountries() : Observable<any>
{
return this.http.GetCountries().subscribe(data => {
return  data;
})
}
GetSelectedCities() : Observable<any>
{
return this.http.GetCities().map(data => {
return   data
});
}
let cities = [{name:'new york', id:1},
{name:'paris', id:2},
{name:'london', id:3}]
let countries = [{name:'usa', id:1, city:'new york'},
{name:'germany', id:2,city:'berlin'},
{name:'france', id:3,city:'marseille'},
{name:'netherland', id:3,city:'amersterdam'}]
GetNotSelectedCities()
{
this.GetCountries.do(data => {
this.GetSelectedCities.do(response => {
data.filter(x=> return response.filter(d=> d.city !== x.name ) )
})
})
}

但我得到的是城市列表,而不是这个结果:

[{name:'germany', id:2,city:'berlin'},
{name:'france', id:3,city:'paris'},
{name:'netherland', id:3,city:'amersterdam'}]

试试这个:

GetNotSelectedCities() {
forkJoin([
this.GetCountries(),
this.GetSelectedCities(),
])
.pipe(
map(([countries, cities]) => {
return countries.filter(country => !cities.find(c => c.name === country.city));
})
)
.subscribe(notSelected => {
console.log(notSelected);
});
}

或者:

GetCountries() : Observable<any>
{
return this.http.GetCountries();
}
GetSelectedCities() : Observable<any>
{
return this.http.GetCities();
}
let cities = [{name:'new york', id:1},
{name:'paris', id:2},
{name:'london', id:3}]
let countries = [{name:'usa', id:1, city:'new york'},
{name:'germany', id:2,city:'berlin'},
{name:'france', id:3,city:'marseille'},
{name:'netherland', id:3,city:'amersterdam'}]
GetNotSelectedCities()
{
return combineLatest([this.GetCountries(), this.GetSelectedCities()]).pipe(map([countries, cities]) => {
return countries.filter(country => cities.filter(d=> d.city !== country.name ).length > 0 );
}))
}

然而,这将要求您在任何想要使用此组合测试的地方订阅此。

最新更新