首页 > 解决方案 > Angular 尝试获取特定值不起作用

问题描述

我正在尝试从我的 Firestore 集合中获取数据。如果我打印我的 JSON,这将有效。如果我现在想显示一个值,它就行不通。为了获取我的数据,我创建了以下内容:

    interface Note{
      imageUrl: string;
    }

    ngOnInit(): void {
      window.scrollTo(0, 0);
      this.notesCollection = this.afs.collection('PromotedBlogs')
      this.notes = this.notesCollection.valueChanges()
    }

我想在 img 中显示 imageUrl。为此,我尝试了以下方法,但它不起作用,它只显示灰色背景:

<div class="blogrow">
    <div class="blogcolumn" style="background-color:#aaa;" *ngFor="let note of notes | async"  >
        <img src="{{ (note | async).imageUrl}}" width="100%" height="300px">
    </div>
  </div> 

标签: angulargoogle-cloud-firestoreangularfire2

解决方案


这里可能有很多问题。您提供的代码有限,很难说。

我正在假设如果您<div> {{notes | json}} </div>在模板中执行某些操作,它将成功显示您的 JSON。这个假设是基于你的评论:

“如果我打印我的 JSON,这将有效”

一个突出的潜在问题是您重复使用异步管道src以及在图像标签的属性中使用括号。

由于您在循环逻辑 ( *ngFor="let note of notes | async") 中解开 Observable ,因此在访问对象的各个属性时无需再次尝试解开它note。此外,在 Angular 中,您不需要对src图像标签的属性使用“波浪括号表示法”。

您可以尝试更新您的图像标签<img [src]="note.imageUrl" width="100%" height="300px">,看看是否能解决您的问题。

如果不是,您可以尝试对路径进行硬编码以验证您的路径实际上是否正确,例如:<img src="path/to/image.png" width="100%" height="300px">


推荐阅读