angular - 我尝试将数据从我的组件添加到其他组件
问题描述
我正在尝试将数据从主要组件添加到支付组件,但我没有显示为什么?我有来自我在主组件中显示的 API 的数据,现在我想在点击时将此数据添加到我的支付组件中,但没有显示任何内容。
服务
export class BookListService {
url: string = 'http://henri-potier.xebia.fr/books';
item:any=[];
public book: Book[];
constructor(private http: HttpClient) { }
getBookList(): Observable<Book[]> {
return this.http.get<Book[]>(this.url);
}
addToBook() {
this.item.push(this.book);
}
}
付款组件.ts
export class PaymentComponent implements OnInit {
public book: Book;
addedBook: any = [];
constructor(private bookListService: BookListService) { }
ngOnInit(): void {
this.addedBook = this.bookListService.getBookList();
}
}
付款.html
<div *ngFor="let book of addedBook">
<span>{{ book.title }}</span>
<span>{{ book.price | currency }}</span>
</div>
主要组件.ts
export class MainComponent implements OnInit {
bookList: any = [];
constructor(private bookListService: BookListService) { }
ngOnInit(): void {
this.bookListService.getBookList().subscribe(data => {
this.bookList = data
})
}
addButton() {
this.bookListService.addToBook()
alert('item added');
}
}
main.component.html
<div class="grid-container">
<div class="wrapper" *ngFor="let book of bookList" class="form-group">
<div class="product-img">
<img [src]="book.cover" alt="livre" height="420" width="327">
</div>
<div class="product-info">
<div class="product-text">
<h2>{{book.title}}</h2>
<p>{{book.synopsis}}</p>
</div>
<div class="product-price-btn">
<p>{{book.price | currency: 'EUR'}}</p>
<button type="button" (click)="addButton()">buy now</button>
</div>
</div>
</div>
</div>
界面
export interface Book {
title: string;
price: number;
cover:string;
synopsis:string;
}
解决方案
您在返回 Observable 的两个组件中使用相同的函数,因此如果您想要在 payment.component 中使用数据,请使用异步管道或再次订阅。
使用异步管道: payment.html
<div *ngFor="let book of addedBook | async">
<span>{{ book.title }}</span>
<span>{{ book.price | currency }}</span>
</div>
或者您可以直接访问所有添加的服务项目
this.addedBook = this.bookListService.item;
推荐阅读
- java - 为 Oracle 构建一个正则表达式,其中最后 4 个值是 0-9 1-Z 而不是 GIOS 字母
- javascript - ReactJS 中的错误“分配给常量变量”
- django - 通过 lambda 将 Django 应用程序部署到 AWS 时,如何解决此错误“消息”:“端点请求超时”?
- python - 使用 Pandas 像 Xlrd 模块读取 Excel 行
- django - 为什么 Django 3.0.6 使用 url() 函数而不是 path() 函数生成 urlpatterns 变量
- python - 如何在 python 中用一个 ecuation 限制做一个双 Reimann 和
- anaconda - 如何在多用户 Conda 安装中锁定环境?
- javascript - 如何更改画布上圆圈的不透明度
- python - 'OSError: [Errno 22] Invalid argument' 使用 PyPDF2 合并文件时
- angular - 如何对这个错误处理函数进行单元测试?