如果url param不包含空ID,请调用getUserDetails和getOrganization List。 如果url param不包含id,则只需调用getOrganization。 但问题是最新的组合并没有调用方案2。
let [updateUser$, createUser$] = this.route.params
.map((params: Params) => params['id'])
.partition(id => !!id);
updateUser$ = updateUser$
.do(() => {
this.isEdit = true;
})
.flatMap(id => this.userService.getUserById(id))
.map(user => {
let languageId = user['languageId'];
let organization = user['organization'];
let organizationObj = [{ id: organization, text: organization }];
return Object.assign(user, { languageId: [{ id: languageId, text: languageId }] }, { organization: organizationObj });
});
let getOrganization$ = this.userService.getOrganization();
Observable.combineLatest(getOrganization$, updateUser$, (organizationList: any, user: any) => {
return {
organizationList: organizationList,
user: user
};
})
.subscribe((data: any) => {
// pre populate the form
let user = data.user;
if (user) {
Object.keys(user).forEach(key => {
const control = this.userForm.get(key);
if (control) {
control.setValue(user[key]);
control.markAsDirty(true);
}
});
}
this.organizationList = data.organizationList.map(o => o.name);
}, err => this.error(err));
Observable.combineLatest(getOrganization$, createUser$, (organizationList: any) => {
return {
organizationList: organizationList,
};
})
.subscribe((data: any) => {
this.organizationList = data.organizationList.map(o => o.name);
}, err => this.error(err));
我应该如何用rxjs模拟这个问题
答案 0 :(得分:1)
这样的事情会起作用。用http和路由替换虚拟可观察量。这只是一个模拟器。
let routes$ = Rx.Observable.create((observer) => {
observer.next({id:1});
setTimeout(()=> observer.next({xx:1}), 1000);
setTimeout(()=> observer.next({id:2}), 2000);
setTimeout(()=> observer.next({xx:2}), 3000);
setTimeout(()=> observer.next({id:3}), 4000);
});
let [updateUser$, createUser$] =
routes$
.map(params=> params['id'])
.partition(id => !!id);
updateUser$
.switchMap(id=>Rx.Observable.of(`${id}_user`))
.switchMap(user=>Rx.Observable.of('organizationList'),
(user, organizationList) => ({user, organizationList})
).subscribe(x=>console.log(x));
createUser$
.switchMap(id=>Rx.Observable.of('organizationList'))
.map(organizationList=> ({organizationList}))
.subscribe(x=>console.log(x));