簡體   English   中英

angular:等待異步數據

[英]angular: wait for asynchronous data

我正在使用 Angular 並嘗試通過將請求發送到后端來驗證我的 service.ts 文件中登錄頁面的用戶憑據。 我想在我的 component.ts 文件中等待服務器響應,但是我做不到。

這是我的代碼:

服務.ts

check_authentication(mail: string, passcode: string)
{
  const params = new HttpParams().set('id', mail).set('id2', passcode);

  this.http.post('http://localhost:3000/login', this.test, {params, responseType: "text"})
  .subscribe(responseData => {
    if(responseData == 'Authorized')
    {
        this.check = true;

    }
    else
    {
        this.check = false;

    }
  }
  ,error => {
    console.log("Error occurred while trying to login "+ error.message);
  });
}

isAuthenticated() : boolean
{
  return this.check;
}

組件.ts

onSubmit()
{
  
  this.auth.check_authentication(this.mail, this.code);

  //this if-else block isn't executing as somehow the response from the server isn't there yet.
  //I want to wait for the response here
  if(this.auth.isAuthenticated() == true)
  {
    console.log("submit button called here");

    this.router.navigateByUrl('/home');
  }
   
  else if(this.auth.isAuthenticated() == false)
  {
    this.unAuthorized = true; //as I am throwing an alert if user login fails
  }

   console.log("Printing this to see if this function is being called correctly"); //this executes 
}

任何幫助,將不勝感激。

check_authenticationl是異步的,這意味着在您檢查用戶是否已通過身份驗證之前,該值尚未准備好。 有幾種方法可以解決這個問題。 一種是讓check_authentication返回一個 Promise。

在服務中:

    check_authentication(mail: string, passcode: string)
    {
      const params = new HttpParams().set('id', mail).set('id2', passcode);
      return new Promise((resolve, reject) => { // create a promise that resolves after the api returns a response

      this.http.post('http://localhost:3000/login', this.test, {params, responseType: "text"})
      .subscribe(responseData => {
        if(responseData == 'Authorized') {
            resolve(true);
        } else {
            resolve(false);
        }
      }, error => {
        console.log("Error occurred while trying to login "+ error.message);
        reject();
      });
    })
      
    }

在組件中

    this.auth.check_authentication(this.mail, this.code).then( isAuth => {
      if(isAuth){

      }else{

      }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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