【问题标题】:Angular : how to deal with Asynchronous issues?Angular:如何处理异步问题?
【发布时间】:2019-05-25 09:33:39
【问题描述】:

我正在努力处理 Angular 6 的异步问题。 这是一个例子。我只想进入'if'并显示控制台日志,但它从未发生过。 getListOne 和 getListTwo 调用 Observable API 并在我的 html 上很好地显示。

ListOne = [];
ListTwo = [];

    ngOninit() {

    this.getListOne();
    this.getListTwo();

    if (this.ListTwo.length > 0 ) {
        console.log("well done at least !";
    }

    }

【问题讨论】:

  • 您最初可以创建listOneLoaded = falselistTwoLoaded = false 之类的变量,在this.getListOne(); this.getListTwo(); 方法中您可以设置它们true 并在您的if 条件中检查这些变量是否变为true

标签: angular asynchronous ngoninit


【解决方案1】:

使用 forkJoin

import { forkJoin } from 'rxjs/internal/observable/forkJoin';  


forkJoin( this.getListOne(), this.getListTwo()).subscribe((result: any[]) => {
       console.log("well done at least !";
}

forkJoin 要求完成所有输入 observable,但它也返回一个 observable,它产生一个值,该值是输入 observable 产生的最后一个值的数组。换句话说,它一直等到最后一个输入 observable 完成,然后产生一个值并完成。

【讨论】:

    【解决方案2】:

    你需要subscribe 来观察像:

    this.getListTwo().subscribe((result) => {
       if(result.length > 0){
        console.log("well done at least !");
       }
    });
    

    但由于这是两个 observable,它们在不同的时间完成,你需要将它们组合起来并订阅组合后的 observable:

    import {combineLatest} from 'rxjs';
    import {tap} from 'rxjs/operators';
    
    combineLatest(
        this.getListOne(),
        this.getListTwo()
    ).pipe(
       tap(([listOneResult, listTwoResult]) => {
         if(listTwoResult.length > 0){
           console.log("well done at least !");
         }
       })
    )
    

    但我认为您需要更多地了解可观察的基础知识。这是关于 Observables 的文档: https://angular.io/guide/observables

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多