Javascript 如何将承诺连接到此链?
我有一个函数,可以检索一个用户的数据。现在我想在这个函数中得到如下用户id:Javascript 如何将承诺连接到此链?,javascript,angular,typescript,ionic-framework,Javascript,Angular,Typescript,Ionic Framework,我有一个函数,可以检索一个用户的数据。现在我想在这个函数中得到如下用户id: this.storage.get(USER_ID).then(val => { this.id = val; )} 因此api知道它需要哪个用户的id。 我必须插入的主要功能是: ngOnInit() { this.subscription = this.authService.authenticationStateSubject.pipe( switchM
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将您的承诺转换为可观察的,并将CombineTest与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
}
);
我真的不知道在哪里为我的id分配val。CombineRelatest会发出一个输入可观测值数组,id已经在数组中。您不需要像从中一样展开承诺。从中我得到一个错误,即对于类型布尔行为主体,它不存在。您将承诺传递给从,而不是行为主体。我已经完成了我的问题是什么意思?但现在我有了一个id,它声明了,但从未读过,我从哪里得到值?