javascript - 如何将承诺连接到这条链?
问题描述
我有一个检索一个用户的数据的功能。现在我想像这样在这个函数中获取 user_id:
this.storage.get(USER_ID).then(val => {
this.id = val;
)}
所以api知道它需要哪个用户的id。我必须插入的主要功能是:
ngOnInit() {
this.subscription = this.authService.authenticationStateSubject.pipe(
switchMap(isAuthenticated => {
if (isAuthenticated) {
return this.userService.getUserDetails(this.id);
} else {
return of(null);
}
}),
).subscribe(
result => {
if (result) {
this.information = result;
console.log(this.information);
} else {
}
},
error => {
}
);
}
我试图将我的代码段放在后面,if (isAuthenticated) {
但不知何故它不适用于最后两个括号。我真的可以连接这两个片段吗?
组合版
ngOnInit() {
this.subscription = this.authService.authenticationState,
from(this.storage.get(USER_ID))
.pipe(
switchMap(([isAuthenticated, id]) => {
if (isAuthenticated) {
return this.userService.getUserDetails(this.id);
} else {
return of(null);
}
}),
).subscribe(
result => {
if (result) {
this.information = result;
console.log(this.information);
} else {
}
},
error => {
}
);
}
解决方案
使用 from 将你的 promise 转换为 observable 并使用 combineLatest 和 authenticationStateSubject
this.subscription = combineLatest(
this.authService.authenticationStateSubject,
from(this.storage.get(USER_ID))
).pipe(
switchMap(
([isAuthenticated, id]) => isAuthenticated ? this.userService.getUserDetails(id) : of(null)
)
).subscribe(
result => {
// do stuff with result
}
);
推荐阅读
- angular - matTable:更改数据源行后 UI 未更新
- c++ - 在 Qt3D 中禁用抗锯齿
- amazon-web-services - 浏览器中 S3 存储桶对象上的 403
- ssl - Plesk > 11 中域的 SSL 证书默认值
- javascript - 离子页面数据不更新
- google-apps-script - 为什么 ClockTriggerBuilder 的 after() 方法运行不正确?
- javascript - ReactJs 中如何提供存储增强器的输入
- c# - AutoMapper 9.x 如何更新现有实体对象
- swift - 如何制作方形视频?
- c# - 从 Azure 云中 Windows Server 上运行的 Active Directory 获取用户