【问题标题】:How can I complete get request then continue execution如何完成获取请求然后继续执行
【发布时间】:2020-10-27 08:28:12
【问题描述】:

我的get request 没有完成,但代码的执行是连续的。因此,因变量没有被初始化。

我正在制作get request,如下所示

export class LoginComponent implements OnInit {

  constructor(public dialog: MatDialog,private objdataService: dataService) { }
  loginsAllRecords:any=[];
  
  //this is calling on button click
  onSubmit(form) {
    this.loadLogins();
    this.validate_user(form.value.name,form.value.password)
  }

  validate_user(username, pin)
  {
    var isEmail;
    var isPassword;

    //this is empty but after execution successfull console.log("data in load ", this.loginsAllRecords) returns data
    console.log(this.loginsAllRecords)
    var email = Object.values(this.loginsAllRecords).filter(x => x.email ==username)
    var password = Object.values(this.loginsAllRecords).filter(x => x.pin ==pin)
  }

  
  async loadLogins() {
     return await this.objdataService.getLogins_service().subscribe((data: {}) => {
      this.loginsAllRecords = data;
      console.log("data in load ", this.loginsAllRecords)
    })
  }

}

在上面的代码中,onSubmit 首先被调用,this.loginsAllRecords 应该被初始化。然后在validate_user() 中调用validate_user()this.loginsAllRecords null。程序执行完成后,this.loginsAllRecords 获取值并在控制台中记录数据。

这是服务类

export class dataService {


  public httpOptions : any;
  loginsAllRecords:any=[];

  public loginUrl="http://localhost:3000/logins";
  constructor(private _http : HttpClient) {
    this.httpOptions = {
        headers: new HttpHeaders(
          { 
            'Content-Type': 'application/json; charset=utf-8',
          }) 
      }
  }

    getLogins_service(): Observable<login> {
    return this._http.get<login>(this.loginUrl)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }  

    // Error handling 
    handleError(error) {
      let errorMessage = '';
      if(error.error instanceof ErrorEvent) {
        // Get client-side error
        errorMessage = error.error.message;
      } else {
        // Get server-side error
        errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
      }
      window.alert(errorMessage);
      return throwError(errorMessage);
   }
}

我该如何解决这个问题?

【问题讨论】:

  • 我猜你是在把 async await 和 observables 混在一起……有什么特别的理由要使用 async await 吗?
  • 异步/等待与承诺一起工作。只有当您等待的异步函数返回一个 Promise 时,它​​们才会起作用。
  • @user1608841 - 我收到了这个错误。我做了谷歌他们建议asyncawait,我补充说。还是同样的问题。没有这些标记也会面临同样的问题。
  • 让我添加一段代码作为答案。

标签: angular typescript httprequest


【解决方案1】:

试试下面的代码:

async/await 使用 Promise。它们仅在您等待的异步函数返回 Promise(不可观察)时才起作用,因此 subscribe 在这里不起作用。

async loadLogins() {
    const data= await this.objdataService.getLogins_service().toPromise();
    this.loginsAllRecords = data;
  }

另一种使用 Observable 的方法:

export class LoginComponent implements OnInit {

  constructor(public dialog: MatDialog,private objdataService: dataService) { }
  loginsAllRecords:any=[];
  
  //this is calling on button click
  onSubmit(form) {
    this.loadLogins(form);
    
  }

  validate_user(username, pin)
  {
    var isEmail;
    var isPassword;

    //this is empty but after execution successfull console.log("data in load ", this.loginsAllRecords) returns data
    console.log(this.loginsAllRecords)
    var email = Object.values(this.loginsAllRecords).filter(x => x.email ==username)
    var password = Object.values(this.loginsAllRecords).filter(x => x.pin ==pin)
  }

  
   loadLogins(form) {
     this.objdataService.getLogins_service().subscribe((data: {}) => {
      this.loginsAllRecords = data;
      this.validate_user(form.value.name,form.value.password)
      console.log("data in load ", this.loginsAllRecords)
    });
  }

}

【讨论】:

  • 您遇到了什么错误?控制台有什么错误吗?
  • 尝试可观察的方法
  • 抱歉打扰了兄弟.. 我刚刚在注册页面中使用了loadLogins(form) 方法,以便我可以检查电子邮件是否已经存在,只是删除了this.validate_user 行。面对同样的问题,方法没有完成,控制继续前进。你能建议吗
  • loadLogin(form) 方法使用的是异步的 http 调用。因此,一旦 http req 满足,则只有 loginAllRecords 可用,因此我在订阅中添加了 validate_user 方法
【解决方案2】:

检查 rxjs 操作符中的 Finalize 返回一个镜像源 Observable 的 Observable,但当源因完成或错误而终止时将调用指定函数。

import { finalize } from 'rxjs/operators';



loadLogins() {
         return this.objdataService.getLogins_service().pipe(
            finalize(() =>  {
             console.log("Done");
             // write your code here
             })
            ).subscribe((data: {}) => {
          this.loginsAllRecords = data;
          console.log("data in load ", this.loginsAllRecords)
        })
      }

finalize 中的代码将在源因完成或错误而终止时执行。

【讨论】:

    【解决方案3】:

    如果你想在 html 部分简单地处理它,你可以简单地在订阅部分使用布尔类型的变量,并在 html 部分使用结构指令。

    例子:

    public loadStuff: boolean = false;
    return await this.objdataService.getLogins_service().subscribe((data: {}) => {
       this.loadStuff = true;
    })
    

    在 HTML 中:

    <div *ngIf="loadStuff">
      ...
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      相关资源
      最近更新 更多