代码之家  ›  专栏  ›  技术社区  ›  Will

异步管道和ngFor不显示项

  •  0
  • Will  · 技术社区  · 5 年前

    *ngFor 迭代 http.get

    服务:

    public getKeywords = () =>  {
       return this.http.get<getKeywords>(`${this.uri}/keywords`);
    }
    

    接口:

    interface getKeywords {
      keywords: Array<object>;
    }
    

    电话号码:

    export class KeywordsSettingsComponent implements OnInit {
    
      public currentKeywords$: any;
    
      constructor(private profileProvider: ProfileProvider) { }
    
      ngOnInit() {
        this.currentKeywords$ =
          this.profileProvider.getKeywords().pipe(map(({ keywords }) => keywords));
      }
    }
    

    <div class="row">
      <ng-template *ngIf="currentKeywords$ | async as currentKeywords ; else loading">
        <div class="keyword" * ngFor="let keywordObj of currentKeywords">
          {{ keywordObj.keyword }}
          <span class="icon-close"> </span>
        </div>
      </ng-template>
      <ng-template #loading> Loading keywords...</ng-template>
    </div>
    

    加载div未显示的事实表明没有发出值。如果我像这样订阅ngOnInt:

     this.currentKeywords$ = this.profileProvider.getKeywords().pipe(map(({keywords}) => keywords), share()).subscribe(res => res));
    

    但是我知道异步管道管理订阅/取消订阅,所以在ngOnInit中订阅应该是不必要的。


    结果来自http.get获取:

    {..."keywords":[{"id":331,"keyword":"spam"},{"id":330,"keyword":"foo"},{"id":332,"keyword":"brexit"}]}
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   Uğur Dinç    5 年前

    基于HTTP正在返回对象这一事实,您需要更改以下内容:

    <div class="keyword" * ngFor="let keywordObj of currentKeywords">
    

    <div class="keyword" *ngFor="let keywordObj of currentKeywords.keywords">
    

    我也会改变这个:

    this.currentKeywords$ =
          this.profileProvider.getKeywords().pipe(map(({ keywords }) => keywords));
    

    this.currentKeywords$ = this.profileProvider.getKeywords();
    

    …因为那张地图并不是真正的地图。

    你可能还需要改变你的第一个 <ng-template 例如 <div ,就像我想象的那样,它不会自己渲染。