html - Angular 9 无法显示图片
我正在使用 Angular 进行训练,我试图显示在注册时发布的文章的头像,但图片没有正确显示。
在 HTML 中:
<ng-container *ngIf="blogpost$ | async as bp; else loading">
<div class="card text-white bg-secondary mb-3" style="max-width: 18rem;">
<img class="card-img-top" [src]="imagePath + bp[0].images">
<div class="card-header">{{ bp[0].title }}</div>
<div class="card-body">
<h5 class="card-title">{{ bp[0].subtitle }}</h5>
<p class="card-text">
{{ bp[0].content }}
</p>
</div>
<i class="material-icons" style="cursor: pointer;" [routerLink]="['edit']">
edit
</i>
</div>
</ng-container>
<ng-template #loading>Loading post ...</ng-template>
这个 [src]="imagePath + bp[0].images 不起作用,我的 imagePath 变量存储在 environment.ts 中:imagePath= 'http://localhost:3000/'(后端服务器)
图片未显示,我收到了这个错误 “http://localhost:4200/undefined28-09-08_1609.jpg 404 (未找到)”。
[src]="bp[0].images" 这也不起作用。
文章创建组件:
import { Component, OnInit, ElementRef } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { BlogpostService } from '../blogpost-service';
import { Router } from '@angular/router';
@Component({
selector: 'app-blogpost-creation',
templateUrl: './blogpost-creation.component.html',
styleUrls: ['./blogpost-creation.component.css'],
})
export class BlogpostCreationComponent implements OnInit {
creationForm: FormGroup;
fileToUpload: File = null;
uploadPath: string = null;
constructor(private router: Router, private fb: FormBuilder, private blogPostService: BlogpostService) {}
ngOnInit() {
this.createForm();
}
createForm() {
this.creationForm = this.fb.group({
title: '',
subTitle: '',
content: '',
images: '',
});
}
createBlog() {
if (this.creationForm.valid) {
if (this.fileToUpload) {
this.blogPostService.uploadImage(this.fileToUpload).subscribe(
data => console.log('image', data),
error => console.log('error', error),
);
}
console.log('formGrp', this.creationForm);
this.blogPostService.createBlogPost(this.creationForm.value).subscribe(
data => console.log('DATA posted', data),
error => this.handleError(error),
);
if (this.creationForm.value) {
this.router.navigate(['']);
}
} else if (this.creationForm.valid) {
this.blogPostService.createBlogPost(this.creationForm.value).subscribe(
data => (this.fileToUpload = null),
error => this.handleError(error),
);
}
}
handleFileInput(event) {
this.fileToUpload = event.target.files[0];
console.log('uploaded file', this.fileToUpload);
}
handleSuccess(data) {
console.log('Post send', data);
}
handleError(error) {
console.log('Error when try to send post', error);
}
}
如果有人有办法加载一张图片!谢谢 :)
答案#1
这个错误很容易理解。
"http://localhost:4200/undefined28-09-08_1609.jpg 404(未找到)"
你在 environment.ts 中定义了 imagePath,但你也需要在你的组件中导入它。
当你写 <img class="card-img-top" [src]="imagePath + bp[0].images"> 时,Angular 会在你的组件中查找定义的 imagePath。
以下内容应该可以解决你的问题
import { environment } from 'environments/environment';
export class BlogpostCreationComponent implements OnInit {
imagePath = environment.imagePath;
}
