img src相对路径以角度4返回未定义的错误

时间:2017-11-17 16:20:45

标签: angular relative-path

我正在尝试使用以下逻辑在我的网站上显示图像: 在组件初始化时,angular将从Web服务器(google firebase)获取img链接。 图像托管在图像主机服务器中,如imgur。 然后组件将更新并显示图像。

但是现在它返回了一个未定义的错误。 详细代码如下所示。

来自home.component.ts的

import { Component, OnInit, OnChanges } from '@angular/core';
import {HttpResponse, HttpEvent} from '@angular/common/http';
import {DbService} from '../db.service';
import {LEDProduct} from '../LED-product.model';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  sampleLEDLinks: LEDProduct[];

  constructor(private dbService: DbService) { }

  ngOnInit() {
    this.dbService.getHomePageImgs().subscribe(
      (returnedLinks: LEDProduct[]) => {
        this.sampleLEDLinks = returnedLinks;
      }
    );

  }

}

来自视图模板

<div class="row" *ngFor="let link of sampleLEDLinks">
  <img  [src]="'//' + link.imgLink" alt="{{link.imgLink}}" width="100">
</div>

LED产品型号模板:

export class LEDProduct {
  public imgLink: string;

  constructor(imgLink: string) {
    this.imgLink = imgLink;
  }

}

现在,我还记录了返回的网址,以确保链接确实返回到应用程序。 这是从chrome

记录返回obj的控制台
(2) [{…}, {…}]
0
:
{link: "i.imgur.com/hy9aFEq.png"}
1
:
{link: "i.imgur.com/JRITacY.gif"}
length
:
2
__proto__
:
Array(0)

但视图仍然为空,并显示如下错误 enter image description here

是因为返回的类型不匹配?我真的很困惑

3 个答案:

答案 0 :(得分:0)

尝试<img *ngIf="link" [src]="'//' + link.imgLink" alt="{{link.imgLink}}" width="100">

编辑: <img *ngIf="link" [src]="'/' + link.imgLink" alt="{{link.imgLink}}" width="100">

或使用主机名

填写完整的绝对网址

答案 1 :(得分:0)

事实证明,当角度接触服务器时,您需要异步获取它。因此我需要使用Async Pipe才能从服务器获取数据。

需要进行一些简单的更改:

  1. 将返回的类型映射到模型 在服务中:

    getHomePageImgsType():Observable {

    return this.httpClient.get<LEDProduct[]>('.../linkList.json')
    .map(
      links=> links
    );
    
  2. 将异步管道添加到对象[] 在视图组件上:

  3. <div class="row" *ngFor="let link of sampleLEDLinks | async">
      <img  [src]="'//' + link.imgLink" alt="{{link.imgLink}}" width="100">
    </div>
    

答案 2 :(得分:0)

app.component.ts中的代码 -

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  sampleLEDLinks = [
    {link: "i.imgur.com/hy9aFEq.png"},
    {link: "i.imgur.com/JRITacY.gif"}
  ]
}

app.component.html中的代码

<img *ngFor="let link of sampleLEDLinks" [src]="'//' + link.link">