【问题标题】:Angular2 image source not showingAngular2图像源未显示
【发布时间】:2021-04-27 04:56:55
【问题描述】:

一段时间以来,我一直在尝试以不同的方式解决问题,但没有任何效果。当我尝试从 unsplash 链接的*ngFor 循环中添加图像源时,出现以下错误:img source not found

我尝试了以下方法:

<img class="slide__image" [src]="slide.urls?.regular">
<img class="slide__image" src="{{slide.urls?.regular}}">

但它也不起作用。在其他方面我得到未知来源或本地主机错误 404。

这里是完整的代码:

import { Component, OnInit, Input } from '@angular/core';
import { Subscription } from 'rxjs';
import { SharedService } from '../shared/shared.service';

@Component({
      selector: 'app-slider',
      templateUrl: './slider.component.html',
      styleUrls: ['./slider.component.scss']
})

export class SliderComponent implements OnInit {
      
      subscriptions: Subscription[] = [];

      currentSlide = 2;
      sliders: any = [];

      constructor(public sharedService: SharedService) { }

      ngOnInit() {

        this.subscriptions.push(
          this.sharedService.showSliders.subscribe((res) =>{
            console.log('first res', res);
            if(res){
              this.sliders.push(...res);
            }else{
              console.log('something went wrong .....');
              
            }
          })
        )

      }


      onSlideClick(index: number) {
        if (this.currentSlide !== index) {
          this.currentSlide = index;

              // document.getElementById('carousel').insertBefore(document.getElementById('carousel').children[4], document.getElementById('carousel').children[0])
              // // add click events to control arrows
              // document.getElementById('prev').addEventListener('click', prev, true);
              // document.getElementById('next').addEventListener('click', next, true);
          };
        }
      

      onPreviousClick() {
        const previous = this.currentSlide - 1
        this.currentSlide = previous < 0 ? this.sliders.length - 1 : previous;
        console.log('previous clicked, new current slide is: ', this.currentSlide);
        if(this.currentSlide === 0){

        }
      }

      onNextClick() {
        const next = this.currentSlide + 1
        this.currentSlide = next === this.sliders.length ? 0 : next;
        console.log('next clicked, new current slide is: ', this.currentSlide, "data :", this.sliders);
        if(this.currentSlide === 4){
          
        }
      }
      
      ngOnDestroy() {
        console.log("component is being destroyed")
        if(this.subscriptions.length > 0){
            this.subscriptions.forEach( (sub) => {
                console.log("subscription removed");
                sub.unsubscribe();
            })
            this.subscriptions = [];
        }
    }

}

    <div class="slider" *ngIf="sliders">
        <ul class="slider__wrapper" [style.transform] = "'translateX(-' + currentSlide * (100 / sliders.length) + '%)'">
        <!-- <ul class="slider__wrapper"> -->
            <li *ngFor="let slide of sliders; let i=index"
            class="slide" 
            #slide
            [class.slide--current]="slide.index === currentSlide" 
            [class.slide--next]="slide.index === currentSlide + 1"
            [class.slide--previous]="slide.index === currentSlide - 1"
            (click)="onSlideClick(slide.index)">
                <div class="slide__image-wrapper">
            <!-- <img class="slide__image" [src]="slide.urls?.regular"> -->
            <!-- <img class="slide__image" src="https://picsum.photos/800/300?image{{i}}" alt="{{slide?.alt_description}}"> -->
                    <img class="slide__image" src="{{slide.urls?.regular}}">
            <div id="blur">
            </div>
              <p class="index-img" >{{slide[i]}}</p>
              <!-- <p class="index-img" >{{[i]}}</p> -->
          </div>
          <p class="description-img">{{slide.alt_description}}</p>
        </li>
      </ul>

      <div class="slider__controls">
        <button class="btn btn--previous" title="Go to previous slide" (click)="onPreviousClick()">
          <svg class="icon" viewBox="0 0 24 24">
            <path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z"></path>
          </svg>
        </button>
        <button class="btn btn--next" title="Go to next slide"  (click)="onNextClick()">
          <svg class="icon" viewBox="0 0 24 24">
            <path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z"></path>
          </svg>
        </button>
      </div>
    </div>

这是对象(我使用 unsplash):

{
"id": "y2lCFKGZEXI",
"created_at": "2021-04-25T10:00:26-04:00",
"updated_at": "2021-04-26T15:54:01-04:00",
"promoted_at": "2021-04-26T15:54:01-04:00",
"width": 4000,
"height": 6000,
"color": "#a673a6",
"blur_hash": "LED96:z=0wx]9?nhxHRO.AV@V@t8",
"description": null,
"alt_description": "pink and white smoke illustration",
"urls": {
    "raw": "https://images.unsplash.com/photo-1619359209643-20df6a2465ad?ixid=MnwyMjU3NTZ8MHwxfGFsbHwzfHx8fHx8Mnx8MTYxOTQ2OTY1MA&ixlib=rb-1.2.1",
    "full": "https://images.unsplash.com/photo-1619359209643-20df6a2465ad?crop=entropy&cs=srgb&fm=jpg&ixid=MnwyMjU3NTZ8MHwxfGFsbHwzfHx8fHx8Mnx8MTYxOTQ2OTY1MA&ixlib=rb-1.2.1&q=85",
    "regular": "https://images.unsplash.com/photo-1619359209643-20df6a2465ad?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMjU3NTZ8MHwxfGFsbHwzfHx8fHx8Mnx8MTYxOTQ2OTY1MA&ixlib=rb-1.2.1&q=80&w=1080",
    "small": "https://images.unsplash.com/photo-1619359209643-20df6a2465ad?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMjU3NTZ8MHwxfGFsbHwzfHx8fHx8Mnx8MTYxOTQ2OTY1MA&ixlib=rb-1.2.1&q=80&w=400",
    "thumb": "https://images.unsplash.com/photo-1619359209643-20df6a2465ad?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMjU3NTZ8MHwxfGFsbHwzfHx8fHx8Mnx8MTYxOTQ2OTY1MA&ixlib=rb-1.2.1&q=80&w=200"
},
"links": {
    "self": "https://api.unsplash.com/photos/y2lCFKGZEXI",
    "html": "https://unsplash.com/photos/y2lCFKGZEXI",
    "download": "https://unsplash.com/photos/y2lCFKGZEXI/download",
    "download_location": "https://api.unsplash.com/photos/y2lCFKGZEXI/download?ixid=MnwyMjU3NTZ8MHwxfGFsbHwzfHx8fHx8Mnx8MTYxOTQ2OTY1MA"
},
"categories": [],
"likes": 49,
"liked_by_user": false,
"current_user_collections": [],
"sponsorship": null,
"user": {
    "id": "ogQykx6hk_c",
    "updated_at": "2021-04-26T16:40:36-04:00",
    "username": "pawel_czerwinski",
    "name": "Paweł Czerwiński",
    "first_name": "Paweł",
    "last_name": "Czerwiński",
    "twitter_username": null,
    "portfolio_url": "http://paypal.me/pmcze",
    "bio": "If you'd like to support me, you can consider a donation ❤ In case you have any questions about how you can use the photos, please read https://help.unsplash.com/en/collections/1463188-unsplash-license ???? ||| www.instagram.com/pmcze",
    "location": "Poland",
    "links": {
        "self": "https://api.unsplash.com/users/pawel_czerwinski",
        "html": "https://unsplash.com/@pawel_czerwinski",
        "photos": "https://api.unsplash.com/users/pawel_czerwinski/photos",
        "likes": "https://api.unsplash.com/users/pawel_czerwinski/likes",
        "portfolio": "https://api.unsplash.com/users/pawel_czerwinski/portfolio",
        "following": "https://api.unsplash.com/users/pawel_czerwinski/following",
        "followers": "https://api.unsplash.com/users/pawel_czerwinski/followers"
    },
    "profile_image": {
        "small": "https://images.unsplash.com/profile-1592328433409-d9ce8a5333eaimage?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32",
        "medium": "https://images.unsplash.com/profile-1592328433409-d9ce8a5333eaimage?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64",
        "large": "https://images.unsplash.com/profile-1592328433409-d9ce8a5333eaimage?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128"
    },
    "instagram_username": "pmcze",
    "total_collections": 20,
    "total_likes": 29503,
    "total_photos": 1070,
    "accepted_tos": true,
    "for_hire": false
}

}

有什么想法吗?

【问题讨论】:

    标签: angular image src


    【解决方案1】:

    通过可选链接,您可以将undefined 传递给 src 属性,直到它被定义...试试这个:

    <div *ngIf="slide.urls" class="slide__image-wrapper">
      <img class="slide__image" [src]="slide.urls.regular">
    </div>
    

    通过在包装 div 上使用 *ngIf="slide.urls",它可以确保在尝试呈现 &lt;img&gt; 之前有一个 urls 对象。

    【讨论】:

    • 它什么都不显示,页面是空白的,但我可以在检查器中看到 10 个元素,但它们是空的
    • 确保您的数据映射正确,您可以添加`{{ slide.urls | json }} 作为要调试的幻灯片图像包装器的兄弟
    • 数据来自一个api,它们已经被映射所以它没有改变任何东西
    • 在您的模板中插入{{ slide.urls | json }} 的目的是您可以验证数据是否正在进入您的模板。如果 正在获取其 src 属性的 url,它应该可以工作。如果它不起作用,则表明您没有正确连接数据。
    • 你不明白。你把{{ slide.urls | json }}放在
      旁边。看看它输出什么。确保有数据。如果没有任何内容,则说明您没有正确接线。
    猜你喜欢
    • 2017-02-04
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    相关资源
    最近更新 更多