gpt4 book ai didi

angular - 避免嵌套的可观察对象

转载 作者:行者123 更新时间:2023-12-05 05:22:38 28 4
gpt4 key购买 nike

我需要填写三个具有层次结构的控件:公司、分支机构、员工。退出用户服务后,我得到了当前登录的用户,然后通过用户的域名我收到他作为员工的完整数据,然后每个员工的 branchId 我获得分支对象,然后我请求所有公司并将控制值设置为当前员工、当前分支机构和当前分支机构的公司。

我最终得到了嵌套的订阅者树。我怎样才能避免这种情况并将其重构为更直接?

this.userService.getCurrentlyLoggedInUser().subscribe(
user => {
this.user = user;
this.getEmployee(this.user.domainName).subscribe(
employees => {
if (employees.length === 0) {
this.isLoading = false;
return;
}
this.getBranch(employees[0].branchId).subscribe(
branches => {
if (branches.length === 0) {
this.isLoading = false;
return;
}
this.odata.companies().subscribe(
companies => {
this.setDefaultValues(companies, branches[0], employees[0]);
this.isLoading = false;
},
error => this.isLoading = false
);
},
error => this.isLoading = false
);
},
error => this.isLoading = false
);
},
error => this.isLoading = false
);

最佳答案

为避免嵌套的订阅调用,您始终可以使用 mergeMap 从元分支映射回主干分支,例如通过某些 AJAX 调用或其他异步操作从主分支 fork 的流

详情请看下面的代码。请注意,只有一个对中继流的订阅调用。所有其他流都被 mergeMap 返回到主干流中,因此不需要额外的订阅。考虑订阅流作为脱离 RxJS 上下文并返回到正常的 JS。这应该只有副作用才需要,例如 console.log 命令。

const initialUserObj = { userId: 0, username: 'admin' };

const getUserGroup = function(id) {
console.log(`Requesting user group for user with id ${id}`); // debug only

const typeAdmin = { group: 'Administrator', rights: 'all' };
const typeUser = { group: 'User', rights: 'restricted' };
const timeout = Math.floor(Math.random() * 5000);

return new Promise((resolve, reject) => {
// Simulated API call with timeout
setTimeout(() => {
resolve(id === 0 ? typeAdmin : typeUser);
}, timeout);
});
}

const getUserDetails = function(id) {
console.log(`Requesting user details for user with id ${id}`); // debug only

const timeout = Math.floor(Math.random() * 5000);

return new Promise((resolve, reject) => {
// Simulated API call with timeout
setTimeout(() => {
resolve({ fullName: id === 0 ? 'Administator himself' : 'Some User' });
}, timeout);
});
}

Rx.Observable.of(initialUserObj)
.flatMap(user => {
return Rx.Observable.fromPromise(getUserGroup(user.userId))
.map(group => Object.assign({}, user, group));
})
.flatMap(user => {
return Rx.Observable.fromPromise(getUserDetails(user.userId))
.map(details => Object.assign({}, user, details));
})
.subscribe(x => console.log(x));

Working sample on jsbin

关于angular - 避免嵌套的可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39846778/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com