【问题标题】:Problem with subscribe and template ionic订阅和模板离子的问题
【发布时间】:2021-02-19 10:34:55
【问题描述】:

我正在尝试显示来自 firebase 存储的图像,如下所示:

在我的组件中:

    findImg(img) {
    this.storage.ref('/img/' + img).getDownloadURL().subscribe(
      result => {
        console.log(result);
      }
    )

在我的模板中:

    <ion-header>
  <ion-toolbar>
    <ion-title>La gamme : {{collectionName}}</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content>
  <ion-card *ngFor="let pro of product | async">
    <ion-card-header>
      <ion-card-title>{{pro.name}}</ion-card-title>
    </ion-card-header>
    <ion-card-content>
      <p>{{pro.img}}</p>
      <div *ngIf="findImg(pro.img)"></div>
    </ion-card-content>
  </ion-card>
</ion-content>

pro.img 是我的产品数据库中字段“img”的名称,也是他存储中图片的名称。

除了带有 ngIf 的 div 之外,一切都有效。在控制台中,结果很好,但显示无限,Chrome 崩溃。我不明白为什么循环永远不会结束。

the bug in image

【问题讨论】:

  • 我的数据库中只有 2 个产品
  • 这可能是因为每次运行更改检测时都会调用此方法findImg(pro.img),这可能就是您在控制台中收到这些消息的原因。您可以尝试用变量替换它吗?
  • 我明白你说的,例如 findImg($myVariable) ?但是我怎样才能得到这个变量?我很抱歉,但我是初级 :) 这应该修改我的代码,但我现在不知道如何隔离这些数据。
  • 没有。在组件本身中订阅product,同时计算图像并将其存储在数组中。在模板上只需遍历数组。
  • 好的,我明天会尝试并卷土重来@NicholasK(取决于我的水平:))

标签: angular typescript observable subscribe ionic5


【解决方案1】:

我尝试了另一种解决方案,获取图像的名称和 url 并将它们发送到一个数组中:

tab: Array<any> = [[], []];

async getImage() {
 return this.storage.ref('img').listAll().subscribe( result => {
  result.items.forEach(imageRef => {
    this.image = imageRef.name;
    this.refImage = imageRef.getDownloadURL().then( url => {
      console.log('My URL : ' + url);
      return this.url = url;
    });
    this.tab.push([this.image, this.url]);
  });
  console.log(this.tab);
});
}

第一个 console.log 有效,但最后一个无效。 this.tab 的第一个值出现,但第二个未定义。我认为我的 getDownloadUrl() 和他的 then 有问题,但我不知道如何解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 2016-03-01
    • 2018-04-04
    相关资源
    最近更新 更多