在Angular 8中,我有2个组成部分:添加书和展示书广告注入服务-book.service。 我从display-book.component.ts搜索预览图像问题。当将其保存在books数组中时,display-book组件将显示该数组中的图像。除了显示图像,标题和描述之外,还可以正常工作。我一直在寻找使用FileReader的方法,但是没有任何效果。
book.service.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class BookService {
constructor() { }
url: any = '';
books: any[] = [];
addBook(imageUrl: string, title: string, description: string) {
const imgUrl: string = imageUrl
const book = {
imgUrl,
title,
description
}
this.books.push(book);
console.log(this.books);
}
}
display-book.component.ts:
import { BookService } from './../services/book.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-display-book',
templateUrl: './display-book.component.html',
styleUrls: ['./display-book.component.scss']
})
export class DisplayBookComponent implements OnInit {
url = this.bookService.url;
books = this.bookService.books;
constructor(private bookService: BookService) { }
ngOnInit() { }
displayBooks(event) {
console.log(this.books)
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event:any) => {
this.url = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
}
}
add-book.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { BookService } from '../services/book.service';
@Component({
selector: 'app-add-book',
templateUrl: './add-book.component.html',
styleUrls: ['./add-book.component.scss']
})
export class AddBookComponent implements OnInit {
addForm: FormGroup;
constructor(private formBuilder: FormBuilder, private bookService: BookService) { }
ngOnInit() {
}
createForm() {
this.addForm = this.formBuilder.group({
BookImageUrl: [''],
BookTitle: [''],
BookDescription: ['']
});
console.log(this.addForm);
}
addBook(imageUrl: HTMLInputElement, title: HTMLInputElement, description: HTMLInputElement) {
this.bookService.addBook(imageUrl.value, title.value, description.value);
}
}
答案 0 :(得分:1)
我只是简单地遍历您在服务中拥有的书籍列表,并使用Angular中的属性绑定语法来呈现它们。像这样:
<ul *ngIf="books.length > 0">
<li *ngFor="let book of books">
<img [src]="book.imgUrl" [alt]="book.title">
</li>
</ul>
<h1 *ngIf="books.length === 0">Add Books to see them here</h1>
这是您推荐的Working Code Sample。