【问题标题】:*ngIf not updating after Object is filled*ngIf 在 Object 被填充后不更新
【发布时间】:2019-02-22 14:25:31
【问题描述】:

我有一个简单的列表页面,我在其中声明了一个通过 API 填充的 pokemons 变量:

export class ListPage implements OnInit { 
public pokemons: any;

constructor(public navCtrl: NavController, public pokemonProvider: PokemonProviderService, public parametersProvider: ParameterProviderService) {
  }


  ngOnInit() {
      this.counter = 1;
      this.pokemonProvider.getPokemons(this.counter).subscribe(result => this.pokemons = result);
      this.counter++;
  }
}

在我看来,我有一个 ngFor,它会循环遍历那些 pokemon 并显示每个 pokemon。

<div *ngIf="pokemons">
<ion-content>
  <ion-list>
    <ion-item *ngFor="let pokemon of pokemons.results" (click)="showDetails(pokemon)">
      <!--<ion-icon [name]="item.icon" slot="start"></ion-icon>-->
      <!--<button ion-button ></button>-->
      <h3> {{pokemon.name}} </h3>

    </ion-item>
  </ion-list>
  <ion-infinite-scroll threshold="100px" (ionInfinite)="loadData($event)">
    <ion-infinite-scroll-content
            loadingSpinner="bubbles"
            loadingText="Loading more data...">
    </ion-infinite-scroll-content>
  </ion-infinite-scroll>
  <!--
    <div *ngIf="selectedItem" padding>
      You navigated here from <b>{{selectedItem.title }}</b>
    </div>
  -->
</ion-content>
</div>

但是 ngIf 永远不会刷新并且总是显示一个白页。即使“口袋妖怪”被填满。

【问题讨论】:

  • this.pokemons = result;); → 去掉第一个分号
  • 您有任何控制台错误吗?
  • @trichetriche 我已经在我的实际代码中完成了,这只是一个复制错误
  • @tricheriche 根本没有
  • @Roykovic 你的代码没有意义。您只是试图获取索引等于 1 的口袋妖怪。确保此调用返回非空值。控制台记录订阅的返回值并检查它是否符合您的期望。如果它返回空值,你知道为什么 -> 调试 pokemonProvider。 index++ 对您的调用没有任何作用(这里没有循环)。还要确保您的 getPokemons 方法返回任何内容。

标签: angular ionic-framework angular-ng-if


【解决方案1】:

使用 div 包装 ion-content 会导致视图无法呈现。
以下是一个实时工作示例。尝试在 ion-content 上使用 *ngIf。

https://stackblitz.com/edit/ionic-vndmrx

【讨论】:

  • 不敢相信它这么简单。像魅力一样工作,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多