Angular 5将baseURI添加到图像src并且无法动态加载图像

时间:2018-04-05 02:56:34

标签: image angular5

我在angular 5.2.1上工作,我想加载一个src来自服务器的图像

HTML

$when = $request->request->get('when');

图像loader.component.ts

<img #image [src]="cover" class="img-fluid" alt="NO image">

Chrome控制台的结果: http://localhost:4200/(which是连接到变量 import { Component, OnInit, Input, AfterViewInit,ViewChild,ElementRef} from '@angular/core'; import { EventAccessService } from '../../../event/services/event-acces.service'; @Component({ selector: 'loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'] }) export class EventCardComponent implements OnInit, AfterViewInit { @Input('cover') cover: any; @ViewChild("image", {read: ElementRef}) image: ElementRef; constructor(private service: EventAccessService) { } ngOnInit() {} ngAfterViewInit() { console.log(this.image.nativeElement.currentSrc); this.image.nativeElement.src=this.cover console.log(this.image.nativeElement.src); } } 的baseURI(这是图像的完整链接)

因此图像无法加载

请帮助!!

修改

我直接在coverimage.nativeElement.src更改为cover,但仍无变化

1 个答案:

答案 0 :(得分:0)

在这里,我像这样使用RxjS:也就是说,您可以将来自服务器的图像URL放入BehaviorSubject中,如下所示。

.html

<img [src]="photoHandlerService?.userProfilePhotoChanged$ | async" #userProfilePhoto>

.ts

 @ViewChild('userProfilePhoto') userProfilePhoto: ElementRef;

 constructor(public photoHandlerService: PhotoHandlerService) { }

  ngAfterViewInit(): void {
    console.log(this.userProfilePhoto.nativeElement.src);
  }

service.ts

 private profilePhoto: string = 'assets/images/jpgs/profilePhoto.jpg';
 private userProfilePhotoSubject$: BehaviorSubject<string> = new BehaviorSubject<string>(this.profilePhoto);
 userProfilePhotoChanged$: Observable<string> = this.userProfilePhotoSubject$.asObservable();

 constructor()

setUserProfilePhoto(photoUrl: string): void {
    this.userProfilePhotoSubject$.next(photoUrl);
}