使用 angular rxjs 中的另一个可观察对象转换来自一个可观察对象的数据
Transform data from one observable using another observable in angular rxjs
我有两个可观察值:城市和地址。在我的 addresses
数组中,我有一个对象,其中 属性 city_code
有一个值,而 属性 city
是空的。在 cities
我有两个属性的对象。
如何转换 addresses
中的数据?我想通过匹配 city_code
从 cities
数组中获取 city
的值,并将该值放入 addresses
.
中的相应对象中
addresses$ = this.store.select(getAddresses);
cities$ = this.citiesFacade.allCities$;
function getAddressesWithCityName() {
// some code here
}
地址和城市:
export interface Address {
city_code: string;
city: string; // in addresses$ this property is empty and I should get it from cities$
}
export interface City{
city_code: string;
city: string;
}
你可以试试这样:
function getAddressesWithCityName(): Observable<Address[]> {
return forkJoin([addresses$, cities$])
.pipe(map((results: [Address[], City[]]) => {
results[0]
.forEach((address: Address) => address.city = (results[1]
.find((city: City) => city.city_code === address.city_code) as City)?.city);
return results[0];
}));
}
您可以使用 combineLatest()
创建一个基于多个源流的可观察流。
然后,你可以简单地定义如下addresses$
,而不需要getAddressesWithCityName()
方法:
addresses$ = combineLatest([this.store.select(getAddresses), this.cities$]).pipe(
map(([addresses, cities]) => addresses.map(a => {
const city = cities.find(c => c.city_code === a.city_code)?.city;
return { ...a, city };
})
);
我有两个可观察值:城市和地址。在我的 addresses
数组中,我有一个对象,其中 属性 city_code
有一个值,而 属性 city
是空的。在 cities
我有两个属性的对象。
如何转换 addresses
中的数据?我想通过匹配 city_code
从 cities
数组中获取 city
的值,并将该值放入 addresses
.
addresses$ = this.store.select(getAddresses);
cities$ = this.citiesFacade.allCities$;
function getAddressesWithCityName() {
// some code here
}
地址和城市:
export interface Address {
city_code: string;
city: string; // in addresses$ this property is empty and I should get it from cities$
}
export interface City{
city_code: string;
city: string;
}
你可以试试这样:
function getAddressesWithCityName(): Observable<Address[]> {
return forkJoin([addresses$, cities$])
.pipe(map((results: [Address[], City[]]) => {
results[0]
.forEach((address: Address) => address.city = (results[1]
.find((city: City) => city.city_code === address.city_code) as City)?.city);
return results[0];
}));
}
您可以使用 combineLatest()
创建一个基于多个源流的可观察流。
然后,你可以简单地定义如下addresses$
,而不需要getAddressesWithCityName()
方法:
addresses$ = combineLatest([this.store.select(getAddresses), this.cities$]).pipe(
map(([addresses, cities]) => addresses.map(a => {
const city = cities.find(c => c.city_code === a.city_code)?.city;
return { ...a, city };
})
);