我正在将“封装”为服务的http请求作为我的js代码中的服务。
最初,我的代码有点像意大利面条,使用这种方式:
let user;
let business;
// check if the user is authenticated
authenticationService.isAuthenticated().subscribe(authenticated => {
// if is authenticated
if(authenticated) {
// get the user profile data and save it to the user variable
profileService.get().subscribe(data => user = data);
// get the user business data and save it to the business variable
businessService.get().subscribe(data => business = data);
}
});
这是有效的,但令人讨厌。所以我将整个陈述改写为
authenticationService.isAuthenticated()
.pipe(
filter(a => a), // continue only when true
tap(() => {
// as above, get data and save to relative variables
this.profileService.get().subscribe(data => user = data));
this.businessService.get().subscribe(data => business = data));
})
).toPromise();
这更好,但是我认为还有更好的方法可以做到,只是我不知道。
我错了吗?
答案 0 :(得分:1)
您已经在重构方面做得很好,尽管仍有空间使函数更纯净,并且仅输出结果且不会弄乱变量。也请尝试避免嵌套subscribe
const getAuthUser=()=>authenticationService.isAuthenticated()
.pipe(
filter(a => a), // continue only when true
switchMap(() =>
zip(this.profileService.get(),
this.businessService.get())
}
).toPromise();
getAuthUser().then(([user,business])=> ......)