簡體   English   中英

如何等到函數以角度完全執行

[英]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>

您可以使用maptap運算符。 像這樣的東西:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM