【问题标题】:Handling of Observable after Get request using Angular 13使用 Angular 13 在 Get 请求后处理 Observable
【发布时间】:2022-06-11 16:11:06
【问题描述】:

我正在尝试执行获取请求以获取数据,然后填充 <ul>。目前以下代码有效并且数据显示正确,但我正在尝试使用异步管道,因为它会自动处理订阅和取消订阅(据我了解该主题):

  this.dataService.getAllCompetitions()
  .subscribe(competition=> 
    {
      this.competitions = competition;
    }); 

然后是模板:

<div class="competitions-table">
   <ul *ngFor="let comp of competitions?.data">{{comp.name}}</ul>
</div>

现在,当我尝试通过删除初始订阅并将 observable 分配给 this.competitions 变量来实现异步管道时

this.competitions = this.dataService.getAllCompetitions();

然后我相应地更改了模板:

<div class="competitions-table">
    <ul *ngFor="let comp of competitions?.data | async">{{comp.name}}</ul>
</div>

模板中没有显示任何数据,所以我不太确定我哪里出错了,或者我目前对实施不了解。

【问题讨论】:

    标签: httpmodule angular2-observables angular13


    【解决方案1】:

    由于data是getAllCompetitions的Observable`返回的对象的一部分,那么,你需要在使用它之前先map它,如下所示:

    this.competitions = this.dataService
      .getAllCompetitions()
      .pipe(map((res) => res.data));
    

    然后,您可以在组件模板中使用它,如下所示:

    <div class="competitions-table">
      <ul *ngFor="let comp of competitions | async">{{ comp.name }}</ul>
    </div>
    

    或者,您可以直接在组件模板中访问data,如下所示:

    <div class="competitions-table">
      <ul *ngFor="let comp of (competitions | async)?.data">{{ comp.name }}</ul>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多