首页 > 解决方案 > 我尝试将数据从我的组件添加到其他组件

问题描述

我正在尝试将数据从主要组件添加到支付组件,但我没有显示为什么?我有来自我在主组件中显示的 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;
}

标签: angulartypescript

解决方案


您在返回 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;

推荐阅读