![](/img/trans.png)
[英]How to wait until all data is received to complete function in typescript/angular?
[英]How to wait until function executes completely in angular
嗨,我正在尝试以角度获取用户详细信息,并根据我需要执行特定任务的用户值,我能够调用 api 但响应需要一些时间,这就是我无法检查条件的原因。
ngOnInit() {
this.getUserDetails();
if(this.user.PrivacyNotice) //getting undefined here
{
}
else
{
}
}
getUserDetails() {
this.user.Email = "test@test.com";
this.bookingListSubscription =
this.restService.getUserProfile(this.user).subscribe(
data => {
this.user = data;
});
}
这里 user 是 UserVM Model 类型的对象,其中包含 PrivacyNotice 布尔字段
以下是进行api调用的服务方法
getUserProfile(user: UserVM): Observable<any> {
return this.http.post<UserVM>(this.getAPI('FetchUserProfile'),user,
this.httpOptions).pipe(
map(data => data),
catchError(this.handleError<any>('getUserProfile'))
);
}
如果我想检查从 api 返回的布尔标志 PrivacyNotice 的值,那么我该如何实现这一点。
通常,只要您处于加载状态,就会显示加载指示器:
例子:
loading = ture;
ngOnInit() {
this.getUserDetails();
}
getUserDetails() {
this.user.Email = "test@test.com";
this.bookingListSubscription =
this.restService.getUserProfile(this.user).subscribe(
data => {
this.user = data;
if((this.user.PrivacyNotice))
{
------
}
else
{
------
}
loading = false;
});
}
并在您的 *.html
<div *ngIf="loading else #loaded">
Loading...
</div>
<ng-template #loaded>
The data is loaded, display them as you wish
</ng-template>
您可以使用map
或tap
运算符。 像这样的东西:
import { tap } from 'rxjs/operators';
...
ngOnInit() {
this.getUserDetails()
.subscribe((user) => {
if ((this.user.PrivacyNotice))
{
-- -- --
} else {
-- -- --
}
});
}
getUserDetails() {
this.user.Email = "test@test.com";
return this.restService.getUserProfile(this.user).pipe(
tap(data => this.user = data)
);
}
或者更好的是,首先去掉getUserDetails
函数,因为此时它似乎不是很有用:
ngOnInit() {
this.user.Email = "test@test.com";
this.restService.getUserProfile(this.user)
.subscribe((user) => {
if ((this.user.PrivacyNotice))
{
-- -- --
} else {
-- -- --
}
});
}
这可以通过使用布尔值来完成。 在这里我把完成作为一个布尔值。 将数据分配给用户后,布尔值现在将更改为 true,您可以根据需要使用它是否显示调用方法等的微调器...
completed=false;
ngOnInit() {
this.getUserDetails();
if(completed){
if((this.user.PrivacyNotice)) //getting undefined here
{
------
}
else
{
------
}
}
}
getUserDetails() {
this.user.Email = "test@test.com";
this.bookingListSubscription =
this.restService.getUserProfile(this.user).subscribe(
data => {
this.user = data;
this.completed=true;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.