[英]How to connect a promise to this chain?
I have a function that retrieve data of one user.我有一个功能可以检索一个用户的数据。 Now I want to get in this function the user_id like that:现在我想在这个函数中获得 user_id 这样的:
this.storage.get(USER_ID).then(val => {
this.id = val;
)}
so the api knows from which user it need the id.所以api知道它需要哪个用户的id。 My main function I have to insert this is:我必须插入的主要功能是:
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 => {
}
);
}
I tried to put my snippet right after the if (isAuthenticated) {
but somehow it doesn't work with the two last brackets.我试图将我的代码段放在if (isAuthenticated) {
但不知何故它不适用于最后两个括号。 Can I actually connect these two snippets?我真的可以连接这两个片段吗?
combined version组合版
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 => {
}
);
}
Use from to convert your promise to an observable and use combineLatest with the authenticationStateSubject使用 from 将您的承诺转换为 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
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.