【问题标题】:Ionic: Display image from http GET requestIonic:显示来自 http GET 请求的图像
【发布时间】:2016-09-06 10:58:03
【问题描述】:

我正在使用 Ionic-2、angular-2 和 typescript。

根据我的项目要求,我想加载新闻页面中的所有图像。为此,我应该向服务器发出 http GET 请求,然后我得到 JSON 响应。所以现在,我已经使用 angular2 的ngFor 在我的视图中显示了来自 JSON 响应的全部数据。在 JSON 响应中,有一个缩略图属性,我需要显示该图像。缩略图包含值:/assets/images/News-Icon.png

我怎么能做到这一点。任何帮助将不胜感激。:)

我做了什么:

.html 文件包含:

<ion-list>
<ion-item *ngFor="let news of news" (click)="newsDetail(news.id)">
  <ion-thumbnail item-left>
    <img src="news.thumbnail">
  </ion-thumbnail>
  <h2 [innerText]="news.title"></h2>
  <p>{{news.author}}</p>
</ion-item>

【问题讨论】:

    标签: angular typescript ionic2 angular2-template


    【解决方案1】:

    尝试使用 data-src 而不是 src

    <ion-list> 
     <ion-item *ngFor="let news of news" (click)="newsDetail(news.id)">
      <ion-thumbnail item-left>
        <img data-src="{{news.thumbnail}}">
      </ion-thumbnail>
      <h2 [innerText]="news.title"></h2>
      <p>{{news.author}}</p>
     </ion-item>
    </ion-list>
    

    【讨论】:

    • 它不适用于data-src,是的,&lt;h2 [innerText]="{{news.title}}"&gt;&lt;/h2&gt; 给出了模板解析错误。它应该是:&lt;h2 [innerText]="news.title"&gt;&lt;/h2&gt;。无论如何,感谢您的宝贵时间并请回复:)
    • 您在使用 data-src 时遇到什么错误?
    • 我的图像位于 www/data/img/myfiles 下。我的 json 值有“img/filename.jpg”。我正在使用 data-src 获取图像。
    • 不报错,也不显示图片。如果我使用&lt;h2 [innerText]="{{news.title}}"&gt;&lt;/h2&gt;,则会出现错误
    • 我已经为 innerText 编辑了我的答案。您是否使用链接 localhost:8100/assets/images/News-Icon.png 在浏览器中显示您的图像?
    【解决方案2】:

    如下更改您的 HTML 并检查:

    <ion-item *ngFor="let news of news" (click)="newsDetail(news.id)">
      <ion-thumbnail item-left>
        <img [src]="news.thumbnail">
      </ion-thumbnail>
      <h2 [innerText]="news.title"></h2>
      <p>{{news.author}}</p>
    </ion-item>
    

    【讨论】:

    • 感谢兄弟的回复:)我已经尝试过[src],但它不适用于这个。不知道为什么!您对此还有其他想法吗?
    • 您是否在浏览器中检查了该应用程序并检查了其控制台以确保它没有为图像 URL 返回 404 错误?可能是根据您的目录结构未正确设置相对路径。
    • 是的,我检查了 console.log();它没有返回 404 错误。它给了我这样的图像:"thumbnail": "/assets/images/News-Icon.png"
    • 我的意思是在控制台的网络选项卡中,您将看到发送的图像请求并响应他们对该请求的响应。您的图像 src url 将类似于 http://localhost:8100/assets/images/News-Icon.png 如果不是,那么您必须解决 URL 的问题
    • 好的...但是,如果图像不在我的本地 assets/images/News-Icon.png 中并且我只想从 JSON 响应中获取呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    相关资源
    最近更新 更多