我目前正在开发一个ionic 5应用程序,我有2个可观察对象,它们返回2个不同对象类型的数组。我想在一个新的对象类型中混合对象的一些属性,但是我只想在第一个返回值的情况下对服务器进行第二次调用。
的例子:
obs1$: Observable<{id: string, name: string, active: boolean}[]>;
obs2$: Observable<{id: string, location: Location, year: date}[]>;
newObs$: Observable<{id: string, name: string, year: date}[]>;
我想:
- Call
obs1$
- 如果
obs1$
返回值则调用obs2$
,否则返回[]
- 当
obs2$
返回值时,返回两个可观察对象的对象映射结果数组
我添加了一些接口,使代码更容易阅读。我在这里假设你的第一个可观察对象在没有值时返回一个空数组。如果它返回null
,你可能需要删除switchMap
中的.length
。
下面的代码可以正常工作。
interface First {
id: string;
name: string;
active: boolean;
}
interface Second {
id: string;
location: Location;
year: Date;
}
interface Result {
id: string;
name: string;
year: Date;
}
...
const first$: Observable<First[]>; // Make sure it's initialized
const second$: Observable<Second[]>; // Make sure it's initialized
...
const result$: Observable<Result[]> = first$.pipe(
switchMap(firstArray => !firstArray.length
? of([])
: second$.pipe(
map(secondArray => firstArray
.filter(a => secondArray.some(b => a.id === b.id))
.map(a => ({ first: a, second: secondArray.find(b => a.id === b.id) }))
.map(values => ({...values.first, year: values.second.year }))
)
)
)
);
我猜你在上课。你可以这样做。但要确保在映射可观察对象之前初始化它。
obs1$: Observable<{ id: string; name: string; active: boolean }[]>;
obs2$: Observable<{ id: string; location: Location; year: Date }[]>;
newObs$ = this.obs1$.pipe(
switchMap((item) => {
const emptyArray: { id: string; name: string; year: Date }[] = [];
return item? this.obs2$.pipe(
map((item2) => {
const others = item2.map((ent2) => {
const index = item.findIndex(ent1 => ent1.id === ent2.id)
let name = ''
if(index !== -1){
name = item[index].name
}
const id = ent2.id;
const year = ent2.year;
return {name, id, year}
});
return others
}),
)
: of(emptyArray);
}),
);